1

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?

francescalus
  • 30,576
  • 16
  • 61
  • 96
techie
  • 191
  • 12

1 Answers1

0

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
techie
  • 191
  • 12
  • An alternative made possible by Fortran 2018 is here: https://fortran-lang.discourse.group/t/return-an-array-of-strings-from-fortran-to-c/5100/7 – K. Shores Jan 30 '23 at 20:00