【发布时间】:2014-12-20 21:56:40
【问题描述】:
我在将二维数组从 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++)
{
for (int j = 0; j<n; j++)
printf("%.6g \t",dptr[i*n+j]);
printf("\n");
}
}
以下是我的 Fortran 代码:
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
代码运行良好;但是,C 中的数组元素需要重新组织。
注意,为了在 Visual Studio 环境中将 C 函数与 FORTRAN 代码链接,应遵循以下步骤:
- 在静态库项目中编写 C 函数
- 构建 .lib 文件
- 创建 FORTRAN 项目并编写代码
- 将 .lib 文件添加到 FORTRAN 项目中(只需将其添加到源文件中)
- 编译并运行。
谢谢, 阿纳斯
【问题讨论】:
-
我注意到
C#(也可能是其他语言)当传递给FORTRAN时,double的字节顺序受到尊重。如果您的代码适用于float但不适用于double,那么这就是正在发生的事情。 -
浮动和双重都不起作用。是否有将二维数组传递给 C 的特定方法?
-
好的,经过全面研究,我能够通过使用 allocate 命令创建数组,然后将数组第一个元素的地址分配给指针 ptr 来解决问题。然后将该指针(在 Fortran 中)传递给 C 函数。请参阅问题中的代码以获取更多详细信息。
标签: c arrays fortran fortran-iso-c-binding