Thanks Laurence! That makes a lot of sense.
I can confirm that it works also when I pass an array slice.
real(c_double), target :: A(5,2)
A = reshape([1,2,3,4,5,6,7,8,9,10],[5,2])
call C_UsesFortranArray_init(cpp_obj,A(:,2))
print *, C_UsesFortranArray_maxval(cpp_obj) ! prints the value 10
One concern that remains is that the FortranArray
wrapper struct, initialized in the line Vector *vec = new Vector(array);
lives now only as a reference within UsesFortranArray
. I think that using the std::shared_ptr<>
as in:
auto vec = std::make_shared<Vector>(array);
UsesVector *obj = new UsesVector(*vec);
init_ptr->obj = obj;
will create a smart pointer, which will be deallocated once no more objects contain references to it.
(I donβt know if this also works for the pointer to UsesFortranArray
which lives only the Fortran side.)