Reputation: 1
I have an already existing Fortran source code that I am working on adding C to, and am having difficulty with passing an array from C into a Fortran function and then receiving another array back.
It compiles without any errors, but when I attempt to run the code, it says that:
"Dimension of array 'p2' (In Fortran Function) has extent 3 instead of -4537421815 (or some other similar number)"
I am not sure what is going on here. I will attach the two codes below.
NOTE: I have removed a lot of the extra variable initialization lines which I think seems unnecessary for finding the problem.
C function:
#include <stdio.h>
#include <stdlib.h>
extern "C" double* __multiphase_tools_MOD_project(double p1[],double *mydt,int *myi,int *myj,int *myk);
extern "C" void cuda_(int *ptr_band, double *ptr_u, double *ptr_v, double *ptr_w)
{
double *pt_out;
double pt_in[3];
// Loop over the domain and compute fluxes near interfaces
//=======================================================================================
// X FACE
//=======================================================================================
for (k = kmin; k <= kmax; k++)
{
for (j = jmin; j <= jmax; j++)
{
for (i = imin; i <= imax; i++)
{
if (abs(band[i-1][j][k]) <= nband_CFL && abs(band[i][j][k]) <= nband_CFL )
{
for (int n = 1; n < 10; n++)
{
pt_in[0] = pt[0][n][1]; pt_in[1] = pt[1][n][1]; pt_in[2] = pt[2][n][1];
pt_out = __multiphase_tools_MOD_project(pt_in,&neg_dt_uvw,&i,&j,&k);
}
}
}
}
}
return;
}
Fortran Function:
function project(p1,mydt,myi,myj,myk) result(p2)
use math
use iso_c_binding
implicit none
real(WP), dimension(3) :: p2
real(WP), dimension(3), intent(in) :: p1
real(WP), intent(in) :: mydt
integer, intent(in) :: myi,myj,myk
real(WP), dimension(3) :: v1,v2,v3,v4
v1=get_velocity(p1 ,myi,myj,myk)
v2=get_velocity(p1+0.5_WP*mydt*v1,myi,myj,myk)
v3=get_velocity(p1+0.5_WP*mydt*v2,myi,myj,myk)
v4=get_velocity(p1+ mydt*v3,myi,myj,myk)
p2=p1+mydt/6.0_WP*(v1+2.0_WP*v2+2.0_WP*v3+v4)
return
end function project
Upvotes: 0
Views: 561
Reputation: 60088
Fortran functions which return an array actually use a hidden argument and are implemented similarly to subroutines. This is why you can't easily write a compatible C function, because you can't portably determine the hidden argument properties.
For example
function f() result(res)
real :: res(3)
res = [1.,2.,3.]
end
looks in the GCC internal code as
f (struct array1_real(kind=4) & __result)
{
}
I suggest to convert the function to a subroutine. That way you can exactly control the argument (parameter) for the array and you can make a C interface:
subroutine project(p1,p2,mydt,myi,myj,myk) bind(C)
real(WP), dimension(3), intent(out):: p2
...
or you can write a wrapper subroutine which calls your function to maintain the Fortran functionality unchanged.
Upvotes: 3