LoadLibrary and AfxLoadLibrary
Processes call LoadLibrary or LoadLibraryEx to explicitly link to a DLL. (MFC apps use AfxLoadLibrary or AfxLoadLibraryEx.) If the function succeeds, it maps the specified DLL into the address space of the calling process, and returns a handle to the DLL. The handle is required in other functions used for explicit linking—for example,
FreeLibrary. For more information, see Explicit linking.
LoadLibrary attempts to locate the DLL by using the same search sequence that is used for implicit linking.
LoadLibraryEx gives you more control over the search path order. For more information, see Dynamic Link Library Search Order. If the system can't find the DLL or if the entry-point function returns FALSE,
LoadLibrary returns NULL. If the call to
LoadLibrary specifies a DLL module that is already mapped into the address space of the calling process, the function returns a handle of the DLL and increments the reference count of the module.
If the DLL has an entry-point function, the operating system calls the function in the context of the thread that called
LoadLibraryEx. The entry-point function isn't called if the DLL is already attached to the process. That happens when a previous call to
LoadLibraryEx for the DLL hasn't had a corresponding call to the
For MFC applications that load MFC extension DLLs, we recommend that you use
AfxLoadLibraryEx instead of
LoadLibraryEx. The MFC functions handle thread synchronization before loading the DLL explicitly. The interfaces (function prototypes) to
AfxLoadLibraryEx are the same as
If Windows can't load the DLL, your process can attempt to recover from the error. For example, it could notify the user of the error, then ask for another path to the DLL.
Make sure to specify the full path of any DLLs. The current directory may be searched first when files are loaded by
LoadLibrary. If you don't fully qualify the path of the file, a file other than the intended one might be loaded. When you create a DLL, use the /DEPENDENTLOADFLAG linker option to specify a search order for statically linked DLL dependencies. Within your DLLs, use both complete paths to explicitly loaded dependencies, and
AfxLoadLibraryEx call parameters to specify module search order. For more information, see Dynamic-Link Library Security and Dynamic Link Library Search Order.