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?
You could:
1) pass the C++ array to a Fortran BIND(C) procedure that takes an appropriate array argument.
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).
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!