Access array of C++ structs from Fortran?

836 Views Asked by At

In C++, I allocate an array of S. In Fortran, I want to access elements of this array. How can I do this?

C++:

struct S {double a; double b;};
S *arrayOfS;
arrayOfS = (S *)new S[123]; // allocate

Fortran 2003:

USE ISO_C_Binding
TYPE, BIND(C) :: SFortran
REAL(c_double) :: a,b
END TYPE SFortran

S and SFortran should now be interoperable, but I also need to have a way to access the elements of the array declared in C++. I'd like to have SC(5)%a in Fortran correspond to arrayOfS[4].a in C++. How do I declare and set the proper value for Fortran array SC that will have this access?

1

There are 1 best solutions below

3
On

You could:

1) pass the C++ array to a Fortran BIND(C) procedure that takes an appropriate array argument.

SUBROUTINE proc(array) BIND(C, NAME='proc')
  ...
  TYPE(SFortran) :: array(*)

WIth this approach you might also want to pass the size of the array across and make the array argument explicit shape.

b) have the array pointer as an extern "C" global on the C++ side, and then interoperate through a Fortran module variable with BIND(C).

MODULE some_module
  USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_PTR, C_F_POINTER
  ...
  TYPE(C_PTR), BIND(C, NAME='arrayOfS') :: array_ptr
  ...
  ! In a procedure in the module...
  TYPE(SFortran), POINTER :: array(:)
  CALL C_F_POINTER(array_ptr, array, [123])

Again it might suit to have size of the array available separately to avoid hard coding it in the C_F_POINTER reference.

Which approach is best depends on your requirements!