fortran - 如何将 NULL 字符连接到 Fortran 中的字符数组以调用 c 函数?

标签 fortran character f2py fortran-iso-c-binding

我有以下测试功能:

#include <stdlib.h>
#include <stdio.h>

void print_string(char *text);

void print_string(char *text) {
    printf("---\n%s\n---\n", text);
}

以下模块使用 iso c 绑定(bind)封装调用 Fortran 子例程:

module test_c_lib

        use iso_c_binding
        implicit none
                
contains
        
    subroutine test(text)
    
            use iso_c_binding
            
            character,intent(in)       :: text(:)
            
            ! Interface to C function
            interface
                    subroutine c_print_string(t) bind(C, name="print_string")
                            import
                            character(kind=c_char) :: t(:)
                    end subroutine
            end interface
            
            ! Call C function
            print *,"AAAAA"
            print *,text
            print *,"AAAAA"         
            
            call c_print_string(text // C_NULL_CHAR)
            
    end subroutine
    
end module

使用 ISO C BINDINGS 在 Fortran 中定义子例程的方法摘自此文档 link .我进一步封装了一点,因为 f2py 不支持 iso c 绑定(bind)。

我通过makefile编译一切:

$ cat makefile 
f_mod.so:       f_mod.f90 c_lib.o
                f2py -c f_mod.f90 c_lib.o -m f_mod

c_lib.o:        c_lib.c
                gcc -c -fpic c_lib.c -o c_lib.o

它编译但是:

  1. 我收到以下警告:
      150 |                 call c_print_string(text // C_NULL_CHAR)
          |                                    1
    Warning: Character length mismatch (2/1) between actual argument and assumed-shape dummy argument 't' at (1) [-Wargument-mismatch]
  1. 通过 import fmod; 调用时,我得到以下输出; f_mod.test_c_lib.test("Foo"):
     AAAAA
     Foo
     AAAAA
    ---
    8v$
    ---

所以 f2py 正在工作,但是当传递 text//C_NULL_CHAR 作为参数时,它似乎不起作用,因为我从 C 函数输出中得到了垃圾。

最佳答案

你有两个错误:

要使字符虚拟参数与 char * C 参数互操作,t 应该是 assumed size array :

character(kind=c_char) :: t(*)   ! Assumed size, not assumed shape

您还可以使用 CFI_cdesc_t C 类型让 t 成为一个假定的形状数组,或一个假定的长度标量,但这样要高级得多。

即使使 t 假定大小,您也没有工作程序,因为下一个问题:// 的基本性质。

因为 text 是一个(假定形状)数组,所以连接 text//C_NULL_CHAR 是按元素完成的,给出长度为 2 的数组1 text 的每个元素都与 C 空字符连接。然后 C 函数看到输入看起来像 [text(1), C_NULL_CHAR, text(2), C_NULL_CHAR, ...]

要有一个附加了 C_NULL_CHAR 的长度为 1 的字符数组,您需要使用数组构造函数:

call c_print_string([text,C_NULL_CHAR])

1 参数长度为 2 是关于“字符长度不匹配”警告的原因。

关于fortran - 如何将 NULL 字符连接到 Fortran 中的字符数组以调用 c 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68461722/

相关文章:

python - 使用 f2py 公开 "in,out"和 "inplace"版本的子例程

python - python中的fortran子例程导入失败

fortran在openvms中获取系统环境信息

c++ - 完全模拟缺失的不同内置类型(特别是 : char16_t and char32_t)

double - 扩展的 double

java - 您好,尝试根据数组值打印一定数量的字符。 java

c - 字符串的实现

python - 使用 f2py 创建可分发的 Windows python 模块

exception - Fortran 中是否存在异常处理?

fortran - 在制表符处分割线