我有以下测试功能:
#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
它编译但是:
- 我收到以下警告:
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]
- 通过
import fmod; 调用时,我得到以下输出; f_mod.test_c_lib.test("Foo")
:
AAAAA
Foo
AAAAA
---
8v$
---
所以 f2py
正在工作,但是当传递 text//C_NULL_CHAR
作为参数时,它似乎不起作用,因为我从 C 函数输出中得到了垃圾。
最佳答案
你有两个错误:
- 一个 Fortran 假定形状字符数组是 not interoperable用 C 字符指针
//
被处理为elementally
要使字符虚拟参数与 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/