将二维数组从 Fortran 传递给 C [英] Passing a two dimentional array from Fortran to C

查看:43
本文介绍了将二维数组从 Fortran 传递给 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 代码如下:

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 项目.代码运行无错误,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.

请帮忙!

谢谢,阿纳斯

推荐答案

经过进一步研究,我找到了解决此问题的方法如下:

After further research I was able to find a work around this as follow:

以下是我的 C 函数:

The following is my C function:

#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

这篇关于将二维数组从 Fortran 传递给 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆