Josh DeLong
Josh DeLong

Reputation: 475

Pass Fortran string reference to C++ and C++ set the value

I have a simple Fortran App that I'm trying to pass a character reference to the C++ dll method and then have the C++ method set the reference string but I can't get it working. This is just of subset of the full code since I couldn't even get this working.

Fortran Code

program FortranConsoleExample

implicit none

interface 
    !!!
    subroutine reverseString(str_out, str_in, str_in_len) bind(C, name="ReverseString3")
      USE, INTRINSIC :: ISO_C_BINDING

      integer(C_INT), VALUE, INTENT(IN) :: str_in_len
      character, dimension(*), intent(IN) :: str_in
      character(kind=C_CHAR), dimension(512), intent(out) :: str_out
    end subroutine reverseString
end interface

! Variables
character*512 :: strResult

call reverseString(strResult, "tacobell", len(strResult))
print *, strResult


end program FortranConsoleExample

C++ Code

extern "C"
{
    __declspec(dllexport) void __cdecl ReverseString3(char * buff, const char *text, int buffLen)
    {
        buff = "yellow";
    }
}

Upvotes: 1

Views: 161

Answers (1)

Edmondo Giovannozzi
Edmondo Giovannozzi

Reputation: 438

Well if you write:

void  ReverseString3(char * buff, const char *text, int buffLen)
    {
        strncpy(buff,"yellow", 6);
    }

It will work, you have to take care of initializing to " " the string in the Fortran part with something like:

strResult = " "

Have a look at Assigning strings to arrays of characters

with the instruction buff = "yellow" you have assigned to the variable buff the address of the string "yellow", leaving the original buffer unchanged.

Upvotes: 4

Related Questions