2
votes

I have a problem with connecting Fortran program with C++ function. My task is to call C++ function pointer from fortran, example:

// C++ function pointer
double* GetSplinePtr()
{
    return sp;
}

I use iso_c_binding procedure and fortran interface. For non-pointer function i usually use this declaration:

real(kind=c_double) function Name(x,y) bind(c, name='Name')
use iso_c_binding
implicit none
real(c_double), intent(in), value :: x,y
end function Name

But what should I use for function which returns a pointer?

Thanks!

1
What about the type C_PTR, also a component of the module iso_c_binding? - Ross
Are you sure intent(in) and value are allowed at the same time? - Vladimir F
@vladimirf intent(inout) and intent(out) certainly conflict with value, but not intent(in)? - francescalus
Yeas, I remembered the constraint wrong, it is (F2008): C558 An entity with the VALUE attribute shall not have the ALLOCATABLE, INTENT (INOUT), INTENT (OUT), POINTER, or VOLATILE attributes. - Vladimir F
Is it a C or C++ pointer? If it is a C++ pointer, there is name mangling. It should be declared as extern "C" on the C++ side to avoid the name mangling. - cup

1 Answers

3
votes

As Ross comments, you must make the Fortran interface to return the C pointer and do the conversion to a Fortran pointer yourself.

interface
  function GetSplinePtr() result(res) bind(C, name="GetSplinePtr")
    use iso_c_binding
    type(C_ptr) :: res
  end function
end interface

In the calling code you have to call c_f_pointer() from the iso_c_binding module:

  use iso_c_binding

  type(c_ptr) :: p
  real(c_double), pointer :: x

  p = GetSplinePtr()

  call c_f_pointer(p, x)