Fortran / C混合:如何在Fortran中访问动态分配的C数组?

我目前遇到内存问题:我有一个用Fortran编码的主程序,它调用C / C ++子程序来执行某些任务并将数据存储在动态分配的数组中。 问题是我需要在返回Fortran主程序时访问这些数据。 我试图在fortran中声明一个C指针(TYPE(C_PTR))指向数组,但它似乎不起作用。 该数组存在于C子例程中,但是当我回到Fortran主程序时尝试访问它时会出现段错误。 我在这里提供我的代码,任何想法? 谢谢你的帮忙 !!

Fortran语言:

PROGRAM FORT_C use iso_c_binding IMPLICIT NONE interface subroutine call_fc(pX,s) bind(C,name='call_fc_') import integer(c_int) :: s type(c_ptr), pointer :: pX end subroutine end interface integer(c_int) :: i integer(c_int) :: s integer(c_int), pointer :: X(:) type(C_ptr), pointer :: pX s=100 call call_fc(pX,s) call c_f_pointer(pX,X,(/s/)) ! This here provocates a segfault do i=1,s write(*,*), i write(*,*) X(i) end do END 

C子程序:

 #include  #include  using namespace std; extern "C" { void call_fc_(int **x, int *s); void c_func_deallocate(int **x); } void call_fc_(int **x, int *s) { int *y = (int *) malloc(sizeof(int)*(*s)); for(int i=0; i < *s+10; i++) { cout << i << endl; y[i]=i; } *x = y; } void c_func_deallocate(int **x) { free(*x); } 

Outpout:

  1 forrtl: severe (174): SIGSEGV, segmentation fault occurred Image PC Routine Line Source exemple 0000000000402E1F Unknown Unknown Unknown exemple 0000000000402C8C Unknown Unknown Unknown libc.so.6 000000331241ECDD Unknown Unknown Unknown exemple 0000000000402B89 Unknown Unknown Unknown