Using Run-Time Dynamic Linking

You can use the same DLL in both load-time and run-time dynamic linking. The following source code produces the same output as the load-time example in the previous section. The program uses the LoadLibrary function to get a handle to MYPUTS.DLL. If LoadLibrary succeeds, the program uses the returned handle in the GetProcAddress function to get the address of the DLL's myPuts function. After calling the DLL function, the program calls the FreeLibrary function to unload the DLL.

The following example illustrates an important difference between run-time and load-time dynamic linking. If the MYPUTS.DLL file is not available, the application using load-time dynamic linking simply terminates. The run-time dynamic linking example, however, can respond to the error.

// File:  RUNTIME.C
// A simple program that uses LoadLibrary and 
// GetProcAddress to access myPuts from MYPUTS.DLL. 
 
#include <stdio.h> 
#include <windows.h> 
 
typedef VOID (*MYPROC)(LPTSTR); 
 
VOID main(VOID) 
{ 
    HINSTANCE hinstLib; 
    MYPROC ProcAdd; 
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 
 
    // Get a handle to the DLL module.
 
    hinstLib = LoadLibrary("myputs"); 
 
    // If the handle is valid, try to get the function address.
 
    if (hinstLib != NULL) 
    { 
        ProcAdd = (MYPROC) GetProcAddress(hinstLib, "myPuts"); 
 
        // If the function address is valid, call the function.
 
        if (fRunTimeLinkSuccess = (ProcAdd != NULL)) 
            (ProcAdd) ("message via DLL function\n"); 
 
        // Free the DLL module.
 
        fFreeResult = FreeLibrary(hinstLib); 
    } 
 
    // If unable to call the DLL function, use an alternative.
 
    if (! fRunTimeLinkSuccess) 
        printf("message via alternative method\n"); 
} 
 

Because the program uses run-time dynamic linking, you should not link with the import library when creating the program module.