About Dynamic-Link Libraries
Dynamic linking allows a module to include only the information the system needs at load time or run time to locate the code for an exported DLL function. Dynamic linking differs from the more familiar static linking, in which the linker copies a library function's code into each module that calls it.
Types of Dynamic Linking
There are two methods for calling a function in a DLL:
- In load-time dynamic linking, a module makes explicit calls to exported DLL functions. This requires you to link the module with the import library for the DLL. An import library supplies the system with the information needed to load the DLL and locate the exported DLL functions when the application is loaded. For more information, see Load-Time Dynamic Linking.
- In run-time dynamic linking, a module uses the LoadLibrary or LoadLibraryEx function to load the DLL at run time. After the DLL is loaded, the module calls the GetProcAddress function to get the addresses of the exported DLL functions. The module calls the exported DLL functions using the function pointers returned by GetProcAddress. This eliminates the need for an import library. For more information, see Using Run-Time Dynamic Linking.
DLLs and Memory Management
Every process that loads the DLL maps it into its virtual address space. After the process loads the DLL into its virtual address, it can call the exported DLL functions.
The system maintains a reference count for each DLL. When a thread loads the DLL, its reference count is incremented by one. When the process terminates, or when the reference count goes to 0 (run-time dynamic linking only), the DLL is unloaded from the virtual address space.
Like any other function, an exported DLL function runs in the context of the thread that calls it. Therefore, the following conditions apply:
- The threads of the process that called the DLL can use handles opened by a DLL function. Similarly, handles opened by any thread of the calling process can be used in the DLL function.
- The DLL uses the stack of the calling thread and the virtual address space of the calling process.
- The DLL allocates memory from the virtual address space of the calling process.