在Fortran和C之间传递字符串

Kyl*_*S-C 3 c fortran

我在Fortran和C之间传递字符串时遇到问题。

Fortran子例程调用如下所示:

CALL MMEINITWRAPPER(TRIM(ADJUSTL(PRMTOP)), 0, SALTCON, RGBMAX, CUT)
Run Code Online (Sandbox Code Playgroud)

与之配合使用的C具有签名:

int mmeinitwrapper_(char *name,
                    int *igb,
                    REAL_T *saltcon,
                    REAL_T *rgbmax1,
                    REAL_T *cutoff1)
Run Code Online (Sandbox Code Playgroud)

我在不同的地方放了一些打印语句,然后一切正常,直到使用ifort编译为止。在这种情况下,输出如下所示:

  Topology file name:
 coords.prmtop                                                                  
   coords.prmtop
 Topology file name length:          81          13
length in C: 8 
read argument: coords.prmtop??* 
Reading parm file (coords.prmtop??*)
coords.prmtop??*, coords.prmtop??*.Z: does not exist
Cannot read parm file coords.prmtop??*
Run Code Online (Sandbox Code Playgroud)

使用波特兰编译器:

  Topology file name:
 coords.prmtop                                                                    
 coords.prmtop
 Topology file name length:           81           13
length in C: 8 
read argument: coords.prmtop 
Reading parm file (coords.prmtop)
Run Code Online (Sandbox Code Playgroud)

第一组中的长度来自未修剪/未调节弦的Fortran,然后来自修剪/已调节弦。C中的长度为sizeof(name)/sizeof(name[0])

似乎正在传递一段过长的内存,并且在随后的运行中,您会写入不同长度的不良内容(尽管C中报告的长度始终为8)。

有人有什么想法吗?让gdb与Fortran / C组合很好地玩很难。

Seb*_*ien 5

我相信您正在寻找的答案在这里:

使用iso_c_binding的fortran-C桥中的字符串数组

基本上,fortran“知道”字符串的长度,但“不”知道C的长度,因此您必须通过将fortran长度传送给C,然后在C代码中做出适当的反应,让C代码以某种方式知道。

下面的问题从“纯” fortran POV中探讨此问题,并给出了各种答案的一些见解:

Fortran到C,修剪对分配给字符串的空间的影响

请记住,编译器可能会利用一些未定义的或特定于实现的差异来解释观察到的各种行为。

另外,我只是意识到假设sizeof字符串大小会弄错你。它给出了指针的大小。所以sizeof(name)/sizeof(name[0])是一个常量,给出的尺寸char,其本身是在C. 8个字节的恒定sizeof(name)给出了一个字符指针的大小和sizeof(name[0])给出了炭的大小。结果是一个常数8。

  • 另请参阅http://stackoverflow.com/questions/8207997/calling-a-fortran-subroutine-from-c/8208960 (3认同)