如何将C strings(char* cstrings[])数组传递给Fortran子例程?
问题使用iso_c_binding的fortran-C桥接器中的字符串数组肯定是相关的,但答案似乎不正确,甚至不能用GNU Fortran编译.
我目前正在为Fortran代码开发一个C接口,我预计iso_c_binding(我之前使用过的)会让这件事变得轻而易举.到目前为止C字符串数组没有运气......
Fortran子例程应该将一个字符串数组作为参数.在普通的Fortran中,我会写如下内容:
subroutine print_fstring_array(fstring)
implicit none
character(len=*), dimension(:), intent(in) :: fstring
integer :: i
do i = 1, size(fstring)
write(*,*) trim(fstring(i))
end do
end subroutine print_fstring_array
Run Code Online (Sandbox Code Playgroud)
将单个C字符串传递给Fortran的一种方法是作为C指针(c_ptr)(我知道,我也可以使用一个数组character(kind=c_char))
subroutine print_cstring(cstring) bind(C)
use iso_c_binding, only: c_ptr, c_f_pointer, c_loc, c_null_char
implicit none
type(c_ptr), target, intent(in) :: cstring
character(len=1024), pointer :: fstring
integer :: slen
call c_f_pointer(c_loc(cstring), fstring)
slen = index(fstring, c_null_char) - 1
write(*,*) fstring(1:slen)
end subroutine print_cstring …Run Code Online (Sandbox Code Playgroud) 我在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)。 …
我对Fortran 很新.目前我正在编写(或试图编写)一个称为C库的fortran应用程序.
到目前为止,我已经完成了一些工作,但是我仍然坚持使用库中的init函数,它希望argc和argv只是获取调用函数的程序名.
C库需要指向argc和argv的指针:
void init(gint argc, gchar ***argv);
Run Code Online (Sandbox Code Playgroud)
我不知道如何在fortran中表达***argv.其他函数只需要整数,所以我可以毫不费力地使用这个骨架:
interface
subroutine init( argc, argv)
??
end subroutine ee_init
end interface
call init( , )
Run Code Online (Sandbox Code Playgroud)