将二维数组从Fortran传递到C
我很难将二维数组从Fortran传递到C函数。然而,在所有的支持之后,下面的代码是100%功能性的 以下是我的C函数:将二维数组从Fortran传递到C,c,arrays,fortran,fortran-iso-c-binding,C,Arrays,Fortran,Fortran Iso C Binding,我很难将二维数组从Fortran传递到C函数。然而,在所有的支持之后,下面的代码是100%功能性的 以下是我的C函数: #include <stdio.h> void print2(void *p, int n) { printf("Array from C is \n"); double *dptr; dptr = (double *)p; for (int i = 0; i < n; i++) { f
#include <stdio.h>
void print2(void *p, int n)
{
printf("Array from C is \n");
double *dptr;
dptr = (double *)p;
for (int i = 0; i < n; i++)
{
for (int j = 0; j<n; j++)
printf("%.6g \t",dptr[i*n+j]);
printf("\n");
}
}
代码运行良好;但是,C中的数组元素需要重新组织
注意,要在visual studio环境中将C函数与FORTRAN代码链接,应遵循以下步骤:
- 在静态库项目中编写C函数
- 构建.lib文件
- 创建FORTRAN项目并编写代码
- 将.lib文件添加到FORTRAN项目(只需将其添加到源文件)
- 编译并运行
Anas像您传递的数组一样,有两种存储方式—行主数组和列主数组。C使用行主键,fortran使用列主键 您必须按照在fortran中创建的顺序访问C中的数组元素 与其发布代码块,不如在编写代码之前更好地理解它。为了清楚起见,请参见以下内容:
我注意到在
C#
中(其他语言也可能如此),当传递到FORTRAN
时,double
的字节顺序受到尊重。如果您的代码对float
有效,但对double
无效,那么就是这样。float和double都无效。有没有一种特殊的方法可以将二维数组传递给C?好的,经过全面的研究,我通过使用allocate命令创建数组,然后将数组的第一个元素的地址分配给指针ptr,解决了这个问题。然后将该指针(Fortran)传递给C函数。请参阅问题中的代码以了解更多详细信息。虽然问题不清楚“全部错误”,但我认为这不太可能是观察到的问题:请参阅IanH给出的链接(重复)问题中的答案。我找到了一种通过传递指向数组第一个元素的指针来传递2d数组的方法。请看问题中的代码
program linkFwithC
use iso_c_binding
implicit none
interface
subroutine my_routine(p,r) bind(c,name='print2')
import :: c_ptr
import :: c_int
type(c_ptr), value :: p
integer(c_int), value :: r
end subroutine
end interface
integer,parameter ::n=3
real (c_double), allocatable, target :: xyz(:,:)
real (c_double), target :: abc(3,3)
type(c_ptr) :: cptr
allocate(xyz(n,n))
cptr = c_loc(xyz(1,1))
!Inputing array valyes
xyz(1,1)= 1
xyz(1,2)= 2
xyz(1,3)= 3
xyz(2,1)= 4
xyz(2,2)= 5
xyz(2,3)= 6
xyz(3,1)= 7
xyz(3,2)= 8
xyz(3,3)= 9
call my_routine(cptr,n)
deallocate(xyz)
pause
end program linkFwithC