How to call an external DLL from Fortran

How to call an external DLL from Fortran

Does anyone know how to call an external DLL from Intel Fortran? I don't have the source code for the DLL, but I know its exported function name and the details of the list of parameters I need to pass to it.

The DLL is called EMG.DLL and the function inside that I want to call is called EMGSub. I can call it Ok from a C program but I want to do it directly from Fortran.

I have tried doing it using LoadLibrary and GetProcAddress as follows: 

hHandle = LoadLibrary("EMG.DLL"C)
IF (hHandle.EQ.0) THEN
    CALL MSGBOX("Could not load EMG.DLL"C)
ELSE
    hProc = GetProcAddress(hHandle, "EMGSub"C)
    IF (hProc.EQ.0) THEN
        CALL MSGBOX("Could not find EMGSub in EMG.DLL"C)
    ELSE
        CALL MSGBOX("Success!"C)
        CALL EMGSub(A,B,C,D) <= This generates a linker "Unresolved external" error
    ENDIF
ENDIF

I realise that the above won't work because I haven't linked my EMGSub call to the hProc procedure handle. How do I link them and then do the call?

Is there any easier way that avoids the need for LoadLibrary and GetProcAddress?
 

5 Beiträge / 0 neu
Letzter Beitrag
Nähere Informationen zur Compiler-Optimierung finden Sie in unserem Optimierungshinweis.

Use something like:

ABSTRACT INTERFACE
    SUBROUTINE EMGSub(A,B,C,D) BIND(C)
      integer*4 A,B,C,D
    END SUBROUTINE EMGSub
  END INTERFACE

  PROCEDURE(EMGSub), BIND(C), POINTER :: pEMGSub

    hHandle = LoadLibrary("EMG.DLL"C)
    hProc = GetProcAddress(hHandle, "EMGSub"C)
  CALL C_F_PROCPOINTER(hProc, pEMGSub)
  CALL pEMGSub(A,B,C,D)

I am writing this code from scratch. There can be some mistake.

Quote:

Is there any easier way that avoids the need for LoadLibrary and GetProcAddress?

They are used for runtime (explicit) linking.  For load time (implicit) linking you can use an import library for the DLL.  Do you have such a beast (a .lib file that goes with the DLL)?

Either way, you'll need to be mindful that you use the right calling convention, etc

See the DLL\DynamicLoad sample we provide. You can't avoid use of LoadLibrary and GetProcAddress.

Steve - Intel Developer Support

Thanks guys, worked like a charm!!

Kommentar hinterlassen

Bitte anmelden, um einen Kommentar hinzuzufügen. Sie sind noch nicht Mitglied? Jetzt teilnehmen