現在、メモリの問題が発生しています。C/C++ サブルーチンを呼び出していくつかのタスクを実行し、動的に割り当てられた配列にデータを格納する Fortran でコーディングされたメイン プログラムがあります。問題は、Fortran のメイン プログラムに戻ったときに、これらのデータにアクセスできる必要があるということです。Fortran で配列を指す C ポインター (TYPE(C_PTR)) を宣言しようとしましたが、うまくいかないようです。配列は C サブルーチン内にありますが、メインの Fortran プログラムに戻ってアクセスしようとすると、segfault が発生します。ここにコードを示します。何かアイデアはありますか? 助けてくれてありがとう!!
フォートラン:
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 <iostream>
#include <cstdlib>
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);
}
出力:
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