Access array of C++ structs from Fortran? -
in c++, allocate array of s. in fortran, want access elements of array. how can 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 , sfortran should interoperable, need have way access elements of array declared in c++. i'd have sc(5)%a in fortran correspond arrayofs[4].a in c++. how declare , set proper value fortran array sc have access?
you could:
1) pass c++ array fortran bind(c) procedure takes appropriate array argument.
subroutine proc(array) bind(c, name='proc') ... type(sfortran) :: array(*)
with approach might want pass size of array across , make array argument explicit shape.
b) have array pointer extern "c" global on c++ side, , interoperate through fortran module variable 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 procedure in module... type(sfortran), pointer :: array(:) call c_f_pointer(array_ptr, array, [123])
again might suit have size of array available separately avoid hard coding in c_f_pointer reference.
which approach best depends on requirements!
Comments
Post a Comment