I\'ve been held up on this for about a week, now, and have searched forum after forum for a clear explanation of how to send a char* from C to FORTRAN. To make the matter m
My thanks to heraldkl for giving me the solution to this very frustrating problem. I'm posting what I've eventually implemented, which roles the pointer conversion into the interface, meaning the final application can call the C function without having to know about the pointer conversion:
The C function:
// The C declaration header (using __cdecl in a def file):
extern "C" const char* GetLastErrorMessage();
The FORTRAN interface module:
MODULE mINTERFACES
USE ISO_C_BINDING
INTERFACE
FUNCTION GetLastErrorMessagePtr [C, ALIAS: '_GetLastErrorMessage'] ()
USE ISO_C_BINDING
TYPE(C_PTR) :: GetLastErrorMessagePtr
END FUNCTION GetLastErrorMessagePtr
END INTERFACE
CONTAINS ! this must be after all INTERFACE definitions
FUNCTION GetLastErrorMessage()
USE ISO_C_BINDING
CHARACTER*255 :: GetLastErrorMessage
CHARACTER, POINTER, DIMENSION(:) :: last_message_array
CHARACTER*255 last_message
INTEGER message_length
CALL C_F_POINTER(GetLastErrorMessagePtr(), last_message_array, [ 255 ])
DO 10 i=1, 255
last_message(i:i+1) = last_message_array(i)
10 CONTINUE
message_length = LEN_TRIM(last_message(1:INDEX(last_message, CHAR(0))))
GetLastErrorMessage = last_message(1:message_length-1)
END FUNCTION GetLastErrorMessage
And to call this function from a FORTRAN program:
USE MINTERFACES
PRINT *, "--> GetLastErrorMessage: '", TRIM(GetLastErrorMessage()), "'"
My thanks again to heraldkl for providing this solution - I wouldn't have had a clue how do do this without his input.