Passing Fortran integer array to C subroutine only first element passed

柔情痞子 提交于 2019-12-25 06:53:09

问题


I am trying to pass an integer array from Fortran to C but I can only pass the first element of the array.

I have the test program below which reproduces the error. Where am I going wrong?

program test
   use foo

   integer (kind=c_int), allocatable :: hgmu_dose(:)
   allocate (hgmu_dose(0:10))

HGMU_dose(0)=22
HGMU_dose(1)=2
HGMU_dose(2)=3
HGMU_dose(3)=4
HGMU_dose(4)=5
HGMU_dose(5)=6
HGMU_dose(6)=7
HGMU_dose(7)=8
HGMU_dose(8)=9
HGMU_dose(9)=10
HGMU_dose(10)=11

print *, "HGMU_dose=", hgmu_dose 

call  test_interface(hgmu_dose)

end program

module foo
  use ISO_C_Binding 

  implicit none 
  interface  
    subroutine test_interface(dose) bind(C,name="INTERFACE")
      import :: c_int
      import :: c_double
      import :: c_char

      integer (kind=c_int), allocatable :: dose(:)
    end subroutine  
  end interface

end module foo 

With

#include "interface.h"

 namespace interface
{

  extern "C" void INTERFACE (int dose[NDIM])
  {
    for (int i = 0; i < NDIM; i++)
      cout << " dose[" << i << "] = " << dose[i] << endl;
  }
}

回答1:


There are a couple of issues here.

The first is in your definition of the test_interface, interface. You do not need or want the allocatable keyword.

subroutine test_interface(dose) bind(C,name="INTERFACE")

  import :: c_int

  integer (kind=c_int) :: dose(:)

end subroutine

The second is the iso_c_binding will pass by reference. So when you define your function in C it should be accepting a pointer to an array:

void INTERFACE (int *dose[NDIM])

Lastly as a side note, you don't have to define your Fortran array as starting from 0. You can use the Fortran normally starting from 1.



来源:https://stackoverflow.com/questions/22310734/passing-fortran-integer-array-to-c-subroutine-only-first-element-passed

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