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;
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.