The DLL Entry Point
Optionally, you can specify an entry point for every DLL you create, and this entry point is normally invoked automatically every time a process attaches or detaches the DLL. LoadLibraryEx, however, allows you to prevent entry point execution. For implicitly linked (load-time) DLLs, process attachment and detachment occur when the process starts and terminates. In the case of explicitly linked DLLs, LoadLibrary, LoadLibraryEx, and FreeLibrary cause the attachment and detachment calls.The entry point is also invoked when new threads (Chapter 7) are created or terminated by the process.The DLL entry point, DllMain, is introduced here but will not be fully exploited until Chapter 12 (Program 12-4), where it provides a convenient way for threads to manage resources and so-called Thread Local Storage (TLS) in a thread-safe DLL.
BOOL DllMain (
HINSTANCE hDll,
DWORD Reason,
LPVOID Reserved)
The hDll value corresponds to the instance obtained from LoadLibrary. Reserved, if NULL, indicates that the process attachment was caused by LoadLibrary; otherwise, it was caused by implicit load-time linking. Likewise, FreeLibrary gives a NULL value for process detachment.Reason will have one of four values: DLL_PROCESS_ATTACH, DLL_THREAD_ATTACH, DLL_THREAD_DETACH, and DLL_PROCESS_DETACH. DLL entry point functions are normally written as switch statements and return TRUE to indicate correct operation.The system serializes calls to DllMain so that only one thread at a time can execute it (threads are thoroughly discussed starting in Chapter 7). This serialization is essential because DllMain must perform initializations that must be completed without interruption. As a consequence, however, it is recommended that there not be any blocking calls, such as I/O or wait functions (see Chapter 8) within the entry point, because they would prevent other threads from entering. LoadLibrary and LoadLibraryEx, in particular, should never be called from a DLL entry point as that would create additional DLL entry point calls.DisableThreadLibraryCalls will disable thread attachment/detachment calls for a specified DLL instance. Disabling the thread calls can be helpful when threads do not require any unique resources during initialization.