0

I am wondering what the correct way is to return an array from Fortran to C, using the ISO C bindings in Fortran.

1
  • 1
    What is the error that you get? You need to have something to start with. Commented Nov 24, 2013 at 4:54

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

You could return a pointer, but then you would need another procedure to dealocate it. Or call malloc from fortran. Arrays are not first class objects in C.
@VladimirF what about returning a struct that contains the array length and pointer?
That changes nothing. You have to pass the array somehow in any case, that is not the point. The point is you also need a way how to deallocate it.
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.