问题描述
在 C++ 和 Fortran 之间传递一个固定的 2D 数组可以正常工作,但我编写的将 2D 动态数组从 C++ 传递到 Fortran 的程序则不然.
Passing a fixed 2D array between C++ and Fortran works fine, however not so with the program I have written to pass a 2D dynamic array from C++ to Fortran.
C++ 端
extern "C" {void array2d_(double **, int *, int *); }
using namespace std;
int main()
{
double **array;
int nx=3;
int ny=2;
int i,j;
cout << "Passing dynamic array from C to Fortran
";
array = (double **) malloc(nx * sizeof(double *));
if(array == NULL)
{
fprintf(stderr, "out of memory
");
exit;
}
for(i = 0; i < nx; i++)
{
array[i] = (double *) malloc(ny * sizeof(double));
if(array[i] == NULL)
{
fprintf(stderr, "out of memory
");
exit;
}
}
for(i = 0; i < nx; i++)
{
for(j = 0; j < ny; j++)
{
array[i][j]=i+j+i*(2+j)+4; //random initialisation
cout << "array[" << i << "][" << j << "]=" << array[i][j] << " ";
}
cout << endl;
}
array2d_(array, &nx, &ny);
for(i = 0; i < nx; i++)
free(array[i]);
free(array);
return 0;
}
fortran 方面
subroutine array2d(arr,nx_C,ny_C) bind(C,name="array2d_")
use iso_c_binding
implicit none
integer (C_INT), intent(IN) :: nx_C,ny_C !array sizes from C
real (C_DOUBLE), intent(INOUT) :: arr(ny_C,nx_C)
integer :: k,l
print *, "This is in Fortran routine..."
do k = 1,ny_C
do l=1,nx_C
print *, "arr(",k,",",l,") = ", arr(k,l)
end do
end do
end subroutine array2d
C++ 中的输出是
array[0][0]=4 array[0][1]=5
array[1][0]=7 array[1][1]=9
array[2][0]=10 array[2][1]=13
在 Fortran 中,输出是
While in Fortran the output is
arr( 1 , 1 ) = 1.7994937190948764E-305
arr( 1 , 2 ) = 7.1027035167764720E-251
arr( 1 , 3 ) = 9.8813129168249309E-324
arr( 2 , 1 ) = 5.4809152658772852E-317
arr( 2 , 2 ) = 1.5475240269406953E-314
arr( 2 , 3 ) = 0.0000000000000000
所以不知何故这些值没有正确传递.
So somehow the values are not passed correctly.
推荐答案
主要原因是你的 C 数组是一个锯齿状数组,它是一个指向分隔一维数组的指针数组,而在 Fortran 中,你将参数声明为一个连续的二维数组.两个部分必须使用相同的,最好在 C 中也使用连续数组.
The main reason is that your C array is a jagged array, it is an array of pointers to separate 1D arrays while in Fortran you declare ther argument to be a contiguous 2D array. You must use the same in both parts, preferably use a contiguous array in C too.
只需 malloc
一个大的 nx*ny
缓冲区并将指针设置为行而不是分配它们.您可以在 https://stackoverflow.com/a/5901671/721644
Just malloc
one big nx*ny
buffer and set the pointers to the rows instead of alloacating them. You can see an example in https://stackoverflow.com/a/5901671/721644
这篇关于将动态二维数组从 C++ 传递到 Fortran 并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!