The code is an example of the Fortran main program calls the C function with an integer array pointer return. The problem is I want to assign a Fortran pointer to a Fortran array with C array value, so I let the Fortran pointer to pointed to two targets at the same time. I know it is wrong now. But since the Fortran does not have some operation like *p, how could I do to make the Fortran array has the same value as an assigned Fortran pointer?
the fortran main code is here:
program Test
use, intrinsic :: iso_c_binding, only : c_ptr, &
c_f_pointer, &
c_int
USE FTN_C
type(c_ptr) :: c_p
integer(c_int), pointer :: f_p(:)
integer, target :: Solution(10)
c_p = C_LIBRARY_FUNCTION()
call c_f_pointer(c_p, f_p, [10])
!c_f_pointer assigns the target, cptr, to the Fortran pointer,
fptr, and specifies its shape.
f_p => Solution ! Solution cannot be pointed
print *, f_p
print *, Solution
end program Test
C code is here:
int* C_Library_Function(){
static int r[10];
for (int i = 0; i < 10; ++i){
r[i] = i;
}
return r;
}
The result shows:
./a.out
0 1 2 3 4 5 6 7 8 9
337928192 1 338811792 1 1073741824 0 337933009 1 338567264 1
FYI the ISO_C_Binding Module code is
MODULE C_Binding
USE, INTRINSIC :: ISO_C_BINDING
END MODULE C_Binding
module FTN_C
INTERFACE
FUNCTION C_LIBRARY_FUNCTION() BIND(C,&
NAME='C_Library_Function')
USE C_Binding
IMPLICIT NONE
type(C_PTR) :: C_LIBRARY_FUNCTION
END FUNCTION C_LIBRARY_FUNCTION
END INTERFACE
end module FTN_C