Reputation: 3611
I am wondering what the correct way is to return an array from Fortran to C, using the ISO C bindings in Fortran.
Upvotes: 0
Views: 437
Reputation: 1556
function return_an_array result(res) bind(c)
use iso_c_binding
implicit none
interface
function malloc(n) bind(c,name='malloc')
use iso_c_binding
type(c_ptr)::malloc
integer(c_size_t),value::n
end function malloc
end interface
type,bind(c)::c_array_2d
type(c_ptr)::p
integer(c_int)::dims(2)
end type
type(c_array_2d)::res
integer(c_size_t)::res_len
real(c_double),pointer::a(:,:)
res_len = 3*2*c_double
res%p = malloc(res_len)
res%dims = [3, 2]
call c_f_pointer(res%p, a, [2,3])
a(1,1) = 1.0
a(2,1) = 2.0
a(1,2) = 3.0
a(2,2) = 4.0
a(1,3) = 5.0
a(2,3) = 6.0
end function
Upvotes: 0
Reputation: 29401
Simple example:
#include <stdio.h>
#include <stdlib.h>
void F_sub ( float * array_ptr );
int main ( void ) {
float * array_ptr;
array_ptr = malloc (8);
F_sub (array_ptr);
printf ( "Values are: %f %f\n", array_ptr [0], array_ptr [1] );
return 0;
}
and
subroutine F_sub ( array ) bind (C, name="F_sub")
use, intrinsic :: iso_c_binding
implicit none
real (c_float), dimension (2), intent (out) :: array
array = [ 2.5_c_float, 4.4_c_float ]
end subroutine F_sub
Upvotes: 1