Creating a FORTRAN interface to a C function that returns a char*

后端 未结 7 1346
天涯浪人
天涯浪人 2020-12-01 10:11

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

相关标签:
7条回答
  • 2020-12-01 10:41

    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.

    0 讨论(0)
提交回复
热议问题