将Fortran数组传递给C

我在将Fortran数组传递给C程序时遇到了很多麻烦。 从我以前的post收集到的是包含界面。 这摆脱了我的一些问题。 但是,我似乎无法弄清楚如何正确传递这些数组或在C内正确访问它们的值。

program f_call_c implicit none interface subroutine cfun(x,len) bind( c ) use,intrinsic :: iso_c_binding implicit none integer( c_int) :: len real(c_double) :: x(0:3,0:len) end subroutine cfun subroutine vec(r,len) bind(c) use,intrinsic :: iso_c_binding implicit none integer(c_int) :: len real(c_double) :: r(0:len) end subroutine vec end interface double precision, allocatable :: x(:,:),r(:) integer :: len,row,i,j len = 7 allocate(x(0:3,0:len)) allocate(r(0:len)) do i =0,len r(i) = i enddo do i = 0,len do j = 0,3 x(j,i) = j+i enddo enddo call vec(r,%val(len) ) row = 3 call cfun(x,%val(len)) end program f_call_c #include  void cfun(double **x,const int len) { printf("%d\n", len); printf("This is in C function cfun...\n"); for(int i=0; i<len; i++) { printf(" %d\n %d\n %d\n", x[0][i]); } } void vec( double *r[],const int len ) { printf("This is in C function vec...\n"); printf("%d\n", len); for(int i=0; i<len; i++) { printf(" %d\n", r[i]); } } 

目前,输出是

  Fortran calling C, passing r at 0 is 0.0000000000000000 r at 1 is 1.0000000000000000 r at 2 is 2.0000000000000000 r at 3 is 3.0000000000000000 r at 4 is 4.0000000000000000 r at 5 is 5.0000000000000000 r at 6 is 6.0000000000000000 r at 7 is 7.0000000000000000 This is in C function vec... 7 0 0 0 0 0 0 0 7 This is in C function cfun... Segmentation fault (core dumped) 

有什么建议?

你不能在c中将fortran数组称为double ** ,它应该是double * ,所以试试这个

 #include  void cfun(double *x, const int len) { printf("%d\n", len); printf("This is in C function cfun...\n"); for (int i = 0 ; i < len ; i++) { printf(" %d\n %d\n %d\n", x[i]); } } 

事实上,如果你有ac double **指针数组,你应该将数组连接成一个数组,将它传递给fortran,例如,参见如何在c中使用Lapack 。

原因是在fortran中,2d数组是连续存储的,而在c中, double **是一个指针数组,因此这些值不是连续存储的。

请注意,在打印值时,您将打印错误的值,因为您没有使用适当的格式说明符为double您应修复printf其看起来像这样

 printf(" %f\n %f\n %f\n", x[i]);