Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29235 Discussions

How to call an external DLL from Fortran

schulzey
New Contributor I
2,054 Views

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?
 

0 Kudos
4 Replies
ZlamalJakub
New Contributor III
2,054 Views

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.

0 Kudos
IanH
Honored Contributor III
2,054 Views

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

0 Kudos
Steven_L_Intel1
Employee
2,054 Views

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

0 Kudos
schulzey
New Contributor I
2,054 Views

Thanks guys, worked like a charm!!

0 Kudos
Reply