将2d数组从Fortran传递到C [英] Passing 2d array from Fortran to C
问题描述
我很难将2D数组从Fortran传递到C函数.但是,毕竟支持,下面的代码可以100%起作用.
I am having difficulty passing a 2d array from Fortran to C function. However, after all the support the following code is functional 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代码:
The following is my Fortran code:
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中的数组元素需要重新组织.
The code runs fine;however, the array elements in C need to be re-organized.
注意,要在Visual Studio环境中将C函数与FORTRAN代码链接,应遵循以下步骤:
Note, In order to link the C function with the FORTRAN code in a visual studio environment, one should follow the following step:
- 在静态库项目中编写C函数
- 构建.lib文件
- 创建FORTRAN项目并编写代码
- 将.lib文件添加到FORTRAN项目中(只需将其添加到源文件中)
- 编译并运行.
谢谢, 阿纳斯(Anas)
Thanks, Anas
推荐答案
像传递的数组有两种存储方式-ROW-MAJOR和COLUMN-MAJOR. C使用行优先,fortran使用列优先.
There are two ways arrays like you are passing are stored - ROW-MAJOR and COLUMN-MAJOR. C uses row-major, fortran uses column-major.
您将必须按照在Fortran中创建的顺序访问C中的数组元素.
You will have to access the array elements in C in the order as it was created in fortran.
与其发布代码块,不如在编写代码之前更好地理解它.为了清楚起见,请参见以下内容: http://en.wikipedia.org/wiki/Row-major_order
Rather than post a code block, you might do better to understand it before you code it. See this for clarity: http://en.wikipedia.org/wiki/Row-major_order
这篇关于将2d数组从Fortran传递到C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!