简体   繁体   中英

Passing string array from Fortran to C/C++ DLL and get array with changed values

I am creating a C/C++ DLL which accepts char*[] (String array), changes the value in array and return back.

My C/C++ implementation:

int doubleijk_(char* data[]) // what should be the return type ???
{
   // code to change array elements

   return 0;
}

In Fortran (using ifort) I am calling the DLL's function like this:

module variables
  type string
    character(len=:), allocatable :: str
  end type string
end module variables


program Call_CPP
    use variables
    type(string) :: array(3) 
    array = [string('xyza'), string('abcd'), string('mnopqrs')]

    INTERFACE
! How to write SUBROUTINE for array

       SUBROUTINE doubleijk_(arr) BIND(C,NAME='doubleijk_')

!???????WHAT SHOULD BE SUBROUTINE FOR ARRAY OF STRINGS????????

       END SUBROUTINE doubleijk_

    END INTERFACE

    ! Body of Call_CPP

    call doubleijk_(array)

 ! print values of array after call

    end program Call_CPP

I am able to pass string, integer from Fortran and got changed value from C/C++. What I need is to pass string array from Fortran to C/C++ and get back the array with changed values. How do I do this?

Finally made that working. Here is the solution.

 program Call_CPP
 use iso_c_binding, only: c_associated, c_loc, c_ptr

    INTERFACE
       SUBROUTINE doubleijk_(stringPtrs) BIND(C,NAME='doubleijk_')
        use iso_c_binding      
        TYPE(C_PTR), DIMENSION(3) :: stringPtrs

       END SUBROUTINE doubleijk_

    END INTERFACE

    TYPE(C_PTR), DIMENSION(3) :: stringPtr
    CHARACTER(LEN=20), DIMENSION(3), TARGET :: stringArray
       DO ns = 1, 3
           stringArray(ns) = "My String"//char(0)
           stringPtr(ns) = c_loc(stringArray(ns))
       END DO

    ! Body of Call_CPP

    call doubleijk_(stringPtr) !Call C function

     DO ns = 1, 3
            print *, stringArray(ns) !print array after call-changed values
     END DO

    end program Call_CPP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM