我正在尝试将字符串数组从 C 传递到 Fortran 子例程,以及从 Fortran 传递到同一个 Fortran 子例程。我已经成功地从 C 和 Fortran 传递了单个字符串(即一维字符数组)。但是,我遇到了字符串数组的问题。我在 Fortran 端使用 ISO C 绑定,理想情况下我希望这在调用端尽可能无缝。
我已经阅读了一些相关的问题和答案。有些(即this和this)只是“使用 ISO C”而没有进一步的细节,这没有多大帮助。这个答案非常有帮助(对不同问题的类似答案),但仅适用于单个字符串,其中似乎 c_null_char 在单个 Fortran 字符串中被识别。如果没有两个单独的例程,我无法弄清楚如何处理数组案例。
我目前拥有的是一个 C 例程,我想从以下位置传递字符串数组 ( string
):
#include <iostream>
extern "C" void print_hi_array(char input_string[][255]);
using namespace std;
int main() {
char string[3][255] = {"asdf","ghji","zxcv"};
print_hi_array(string);
return 0;
}
并且,一个类似的 Fortran 例程:
program main
implicit none
call print_hi_array( (/"asdf", "ghji", "zxcv"/) )
end program
到目前为止,这是我为接收端所拥有的:
subroutine print_hi_array(input_string) bind(C)
use iso_c_binding, only: C_CHAR, c_null_char
implicit none
character (kind=c_char, len=1), dimension (3,255), intent (in) :: input_string
character (len=255), dimension (3) :: regular_string
character (len=255) :: dummy_string
integer :: i,j,k
write (*,*) input_string
do j = 1 , 3
dummy_string(:) = c_null_char
k = 1
do i = 1 + (j-1)*255, j*255,1
if (input_string(i) .ne. c_null_char) then
write (*,*) "i ",i,j, input_string(i)
dummy_string(k:k) = input_string(i)
endif
k = k +1
enddo
regular_string(j) = dummy_string
enddo
write (*,*) regular_string
end subroutine print_hi_array
这适用于 C 函数;我得到这个输出:
asdfghjizxcv
j= 1
i 1 1 a
i 2 1 s
i 3 1 d
i 4 1 f
j= 2
i 256 2 g
i 257 2 h
i 258 2 j
i 259 2 i
j= 3
i 511 3 z
i 512 3 x
i 513 3 c
i 514 3 v
asdf ghji zxcv
但是,当它通过 Fortran 完成时,我会胡说八道:
asdfghjizxcv@O,B�@(P,B�]B]6(P,B�@ .......
这种方法似乎没有c_null_char
。
那么,如何编写一个 Fortran 子例程来接收来自 C 和 Fortran 的字符串数组?