This is probably a very simple thing I’m missing, but I’m having difficulties passing parameters from Fortran to C. Here are the program listings:
c_func.c:
#include<stdint.h>
#include<stdio.h>
int32_t c_func(int32_t x)
{
printf("in c_func, x: %d\n",x);
return 42;
}
…and the corresponding Fortran:
test_interop.f90:
program test_interop
use iso_c_binding
implicit none
interface
integer(c_int32_t) function c_func(x) bind(c, name="c_func")
use iso_c_binding
integer(c_int32_t), intent(in) :: x
end function c_func
end interface
print *, "c_func(0): ", c_func(0_c_int32_t)
end program test_interop
The program compiles and links without apparent issue:
$ make
gcc -Wall -Wextra -pedantic -c c_func.c
gfortran -Wall -Wextra -c test_interop.f90
gfortran -Wall -Wextra test_interop.o c_func.o -o test_interop
Running the program, I get for example:
in c_func, x: -1878081492
c_func(0): 42
…which shows that the input parameter is bogus (expected 0), but that c_func
is called, prints to stdout
and passes back the 42 correctly as expected. There is nothing special about the c_int32_t
, I’ve also tried c_double
and c_int
, with similar results; the passed in argument is not correct, but the passed back argument works. I’ve tried with: gfortran v13.2.0, v14.0.1 on Ubuntu, and v13.2.0 on Cygwin. All with similar results. On the Ubuntu system, the passed in value changes with every run of the program, which makes it seem like it is passing in a pointer, and this changes from invocation to invocation with the address space layout randomization.
Thanks!