10.2.3 Using Run-time Dynamic Linking

The same dynamic link library can be used in both load-time and run-time linking. The following source code should produce the same output as the load-time example in the previous section. LoadLibrary is used to get a handle to the myputs DLL. If successful, the returned handle is used in GetProcAddress to get a pointer to the myPuts function. After the function pointer has been used, FreeLibrary is called to detach the process from the DLL.

The example illustrates one of the differences between this method of dynamic linking and the load-time linking of the previous section. If this program is unable to call the myPuts function because either LoadLibrary or GetProcAddress fails, it can use an alternative method to accomplish the same objective. If the myputs.dll file is not available, the program using load-time linking will simply terminate without printing a message, while the run-time example is able to respond to the error.

/*

* File: runtime.c

* A simple program that uses LoadLibrary and GetProcAddress to

* access myPuts() from the myputs DLL

*/

#include <windows.h>

VOID main(VOID) {

HANDLE hLib;

FARPROC ProcAddr;

BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;

hLib = LoadLibrary("myputs");

if (hLib != NULL) {

ProcAddr = GetProcAddress(hLib, "myPuts");

fRunTimeLinkSuccess = (ProcAddr != NULL);

if (fRunTimeLinkSuccess)

(ProcAddr) ("message printed using the DLL function\n");

fFreeResult = FreeLibrary(hLib);

}

if (!fRunTimeLinkSuccess)

printf("message printed using alternative method\n");

}