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?

3
  • You haven't a "string array" in Fortran. You have an array of a derived type called string. Commented Dec 13, 2017 at 10:05
  • @francescalus Is it achievable?? What will be the correct way to pass array?? Commented Dec 13, 2017 at 10:19
  • 1
    Have you seen this question? Commented Dec 13, 2017 at 10:25

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

An alternative made possible by Fortran 2018 is here: fortran-lang.discourse.group/t/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.