Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
New Contributor I
12 Views

Inconsistent Memory Reference

Jump to solution

Hi, I am doing some mixed programming between C++ and Fortran. A problem comes up about passing a character array from fortran to C++ as shown in the code. The memeory addresses before and after calling the subroutine are not consistant to each other thus the character array is not properly passed. Am I doing it the wrong way or is there anything I have not yet noticed ? Thanks for any help.

PS: The project was debugged on x64 platform.

0 Kudos

Accepted Solutions
Highlighted
Valued Contributor III
12 Views

I will suggest you employ the standard Fortran feature of interoperability with C: your C++ code for your DLL can remain unchanged, but you can try the following with your Fortran program:

module FModule

   use, intrinsic :: iso_c_binding, only : c_char

   implicit none

   interface

      subroutine testchararray(arr) bind(C, name="testchararray")
         import :: c_char
         implicit none
         character(kind=c_char,len=1), intent(in) :: arr(*)
      end subroutine testchararray

   end interface

end module FModule

program Main

   use, intrinsic :: iso_c_binding, only : c_char, c_loc, c_intptr_t
   use FModule, only : testchararray

   implicit none

   integer(c_intptr_t) :: adda

   character(kind=c_char,len=10), dimension(2) :: arr = ["1234567890", "0987654321"]

   write(*,"(z0)") transfer( source=c_loc(arr), mold=adda )
   call testchararray(arr)

end program Main

Look in Intel Fortran documentation for Fortran/C or any books/online resources on modern Fortran.

View solution in original post

0 Kudos
2 Replies
Highlighted
Valued Contributor III
13 Views

I will suggest you employ the standard Fortran feature of interoperability with C: your C++ code for your DLL can remain unchanged, but you can try the following with your Fortran program:

module FModule

   use, intrinsic :: iso_c_binding, only : c_char

   implicit none

   interface

      subroutine testchararray(arr) bind(C, name="testchararray")
         import :: c_char
         implicit none
         character(kind=c_char,len=1), intent(in) :: arr(*)
      end subroutine testchararray

   end interface

end module FModule

program Main

   use, intrinsic :: iso_c_binding, only : c_char, c_loc, c_intptr_t
   use FModule, only : testchararray

   implicit none

   integer(c_intptr_t) :: adda

   character(kind=c_char,len=10), dimension(2) :: arr = ["1234567890", "0987654321"]

   write(*,"(z0)") transfer( source=c_loc(arr), mold=adda )
   call testchararray(arr)

end program Main

Look in Intel Fortran documentation for Fortran/C or any books/online resources on modern Fortran.

View solution in original post

0 Kudos
Highlighted
New Contributor I
12 Views

Thanks for your solution FortranFan.

0 Kudos