5

Suppose that I have a C function with the following API :

int c_function(int **a);

How should I go about declaring a Fortran array/pointer to array, and passing it to the function, assuming that the C function is responsible for memory allocation ?

1
  • I don't think you can. Commented Jun 2, 2015 at 12:20

1 Answer 1

4

You must declare a Fortan c-pointer of type(c_ptr)

type(c_ptr) :: ptr

then call your function (with proper interface)

n = c_function(ptr)

and only then point a Fortran array pointer there

real, pointer :: Array(:)

call c_f_pointer(ptr, Array, [n])

I assumed that n is the size of the array. You must know it, otherwise it is impossible.

The interface could look like

interface

    integer(c_int) function c_function(ptr) bind(C,name="c_function")
      use iso_c_binding
      type(c_ptr) :: ptr
    end function

end interface
Sign up to request clarification or add additional context in comments.

2 Comments

I couldn't find an exact duplicate, just this one stackoverflow.com/questions/30481686/… but that is not very good to point to. Feel free ti find better one.
Thank you, this works perfectly. Although if I'm printing the pointer in the C function, I get the same value for all the processes in my MPI communicator. But it somehow works.

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.