Fortran和C++/C混合编程时,动态内存的传递
本帖最后由 安靖 于 2014-12-27 12:45 编辑在编程工具交流版块中发过类似的帖子http://bbs.fcode.cn/thread-393-1-1.html
现在在动态内存的传递上遇到了问题。在c++中申请内存空间,传给fortran,但是失败了
演示例子
c++, testCPP.cpp
#indef __cplusplus
extern "C"{
int test_fun_(int *i, int *j, int **array);
}#endif
int test_fun_(int *i,int *j,int **array)
{
int a;
array= new*[*j];
for(a = 0; a < *j; a++)
{
array = new int[*i];
}
return 0;
}
fortran文件 testF.f90
program main
implicit none
integer ::i, j
integer, allocatable, dimension(:,:) :: arry
i = 3
j = 4
call test_fun(i, j , arry)
if(allocated(array))then write(*,*) 'sucessful!'
else
write(*,*) 'fail!'
end if
end program
g++-ctestCPP.cpp
ar -cr libtest.a testCPP.o
ifort -c testF.f90
ifort -o test testF.o -L./ -ltest -lstdc++
运行./test
fail
哪里出问题了?
fortran 的 allocatable 基本上没有办法与 C 语言的指针混合使用。
原因在于:
1.fortran的可分配数组比c数组信息量丰富,包括维度,每个维度的上下限,步长,首地址。(可以视为一个结构来描述)
2.C的数组指针只有首地址。
3.fortran的可分配数组结构描述,因不同编译器而不同。
我的建议是:
1.谁定义,谁分配,谁释放;谁打开,谁读写,谁关闭;
2.如果 fortran 定义,那么先通过 C 获得大小,然后由 fortran 分配,传递给 C 使用。 fcode 发表于 2014-12-27 12:41
fortran 的 allocatable 基本上没有办法与 C 语言的指针混合使用。
原因在于:
1.fortran的可分配数组比c数 ...
谢谢你的建议。
页:
[1]