Passing 2d array from Fortran to C

3.1k Views Asked by At

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 1 best solutions below

2
On

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