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

问题描述

我有以下测试功能:

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

void print_string(char *text);

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

以及以下模块,该模块使用 iso c 绑定封装了 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 绑定。

我通过 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 函数输出中得到了垃圾。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)