Sam van der Zwan
Sam van der Zwan

Reputation: 59

Is it possible to pass a c++ vector of pointers to fortran?

I need to pass a vector of pointers from c++ to a Fortran dll and I do not know if this is possible.

I tried searching but I could not really find and answer to my question. The idea is the following:

Fortran side

!DEC$ATTRIBUTES DLLEXPORT :: TO_FORTRAN
      integer function TO_FORTRAN (test4)  BIND(C)
      use, intrinsic :: ISO_C_BINDING
      implicit none
      REAL, intent(in) :: test4(3)
      REAL, pointer :: test5
      call C_F_POINTER(C_LOC(test4),test5)
      TO_FORTRAN = 0
      END

c++ code

std::vector<float> test1(3);
std::vector<float> test2(3);
std::vector<float> test3(3);

std::vector<float*> test4(3);

test4[0] = test1.data();
test4[1] = test2.data();
test4[2] = test3.data();
TO_FORTRAN(test4);

Upvotes: 1

Views: 308

Answers (1)

If it is really an array of pointers, you need to treat it like an array of pointers at the Fortran side as well. You also have keep in mind they are pointers to arrays, not just scale real numbers (although they may be represented the same way in C).

!DEC$ATTRIBUTES DLLEXPORT :: TO_FORTRAN
      integer function TO_FORTRAN (test4)  BIND(C)
        use, intrinsic :: ISO_C_BINDING
        implicit none
        type(c_ptr), intent(in) :: test4(3)
        REAL, pointer :: test1(:), test2(:), test3(:)
        call C_F_POINTER(test4(1),test1, [3])
        call C_F_POINTER(test4(2),test2, [3])
        call C_F_POINTER(test4(3),test3, [3])
        TO_FORTRAN = 0
      END FUNCTION

and

      TO_FORTRAN(test4.data());

Upvotes: 1

Related Questions