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
You never initialized
Solution. There is no reason why it should contain some particular values. It is undefined. Just set the values to something meaningful.The fact, that
f_pused to point toSolutionis irrelevant.The title of your question is very peculiar. It mentions some allocation, but there is no allocation in your code sample. All data is static. There must be some misunderstanding on your side. The C function does not allocate anything. It just contains a static local array and returns a pointer to this local array.
First, you make the
f_ppointer to point to theSolutionarray local to the main program. But then you change the pointer to point to therlocal array in the C function instead. The pointer no longer points toSolution, it points to therinside the C function.Solutionandrare two different independent static arrays.If you wanted to return an array from the C function, as you can return from a Fortran one - it is not possible. You can do various other things instead Returning an array using C but you then somehow copy the data from that result to your array that you want to set yourself. You would also be responsible for the memory management of any temporary allocated for the result. Instead, it is much better to pass a pointer to the Fortran array to the C function and let it set the values directly.