Passing 2d array from Fortran to C [duplicate]

时光怂恿深爱的人放手 提交于 2019-12-12 03:20:04

问题


I am having difficulty passing a 2d array from Fortran to C function. However, after all the support the following code is functional 100%.

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");
     }
  }

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

The code runs fine;however, the array elements in C need to be re-organized.

Note, In order to link the C function with the FORTRAN code in a visual studio environment, one should follow the following step:

  • Write the C function in static library project
  • build the .lib file
  • Create the FORTRAN project and write your code
  • Add the .lib file to the FORTRAN project(just add it to the sources file)
  • Compile and run.

Thanks, Anas


回答1:


There are two ways arrays like you are passing are stored - ROW-MAJOR and COLUMN-MAJOR. C uses row-major, fortran uses column-major.

You will have to access the array elements in C in the order as it was created in fortran.

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



来源:https://stackoverflow.com/questions/27584674/passing-2d-array-from-fortran-to-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!