经过两维数组从Fortran语言为C [英] Passing a two dimentional array from Fortran to C
问题描述
我有传递二维数组Fortran语言,从到C以下问题是我的C函数刚刚在屏幕上显示的数组元素。
I am having trouble passing a two dimensional array from Fortran to C. The following is my C function which just displays the array elements on the screen.
#include <stdio.h>
void print2(double *arr , int *n)
{
int y = *n;
printf("\n y = %d", y);
for(int i =0; i<y; i++)
{
for (int j = 0; j < y; j++)
printf("%.6g", *((arr + i*y) + j));
printf("\n");
}
}
我的Fortran code到目前为止是这样的:
My Fortran code so far is the following:
program linkFwithC
use, intrinsic :: iso_c_binding
implicit none
real, dimension(3,3)::a
a(1,1)=1
a(1,2)=2
a(1,3)=3
a(2,1)=4
a(2,2)=5
a(2,3)=6
a(3,1)=7
a(3,2)=8
a(3,3)=9
interface
subroutine print2(a,n) bind( c )
use, intrinsic :: iso_c_binding
type(c_ptr)::a
integer(C_INT)::n
end subroutine print2
end interface
call print2(c_loc(a),3)
end program linkFwithC
我是连接这两个文件的方式是通过创建C函数静态库并建立的.lib文件。一旦文件.LIB建立我将它添加到FORTRAN项目并运行该Fortran项目。在code没有错误运行,并正确显示n值;然而,显示数组值都是错误的。
The way I am linking both files is by creating a static library for the C function and build the .lib file. Once the .lib file is built I add it to the fortran project and run the fortran project. The code runs with no errors and the n value is displayed correctly; However,the array values displayed are all wrong.
请帮帮忙!
谢谢,
阿纳斯
Thanks, Anas
推荐答案
进一步研究后,我能找到解决这个作品如下:
After further research I was able to find a work around this as follow:
以下是我的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 code:
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
这篇关于经过两维数组从Fortran语言为C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!