Passing a two dimentional array from Fortran to C

前端 未结 2 1429
無奈伤痛
無奈伤痛 2020-12-11 13:17

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.

#         


        
相关标签:
2条回答
  • 2020-12-11 13:29

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

    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
    
    0 讨论(0)
  • 2020-12-11 13:38

    There are a few issues in the code as [currently] shown.

    • The n argument in the Fortran interface for print2 does not have the VALUE attribute, yet the corresponding parameter in the C function is taken by value. Consider adding VALUE to the Fortran declaration.

    • The same issue arises with the pointer to the array. The Fortran interface passes a pointer without value, the C function expects a "pointer by value" (as opposed to a pointer to a pointer). Note that there is no need to explicitly use a C_PTR here - you can construct an interoperable interface using the actual type of the array.

    • On most platforms a Fortran default REAL is not the same as a C double - consider using the kind constants from ISO_C_BINDING to ensure that the kind of the REAL on the Fortran side matches that of the C.

    • C_LOC requires its argument to have the TARGET attribute. Add that attribute to the declaration of the a variable in the main program.

    0 讨论(0)
提交回复
热议问题