|
The DllMain function is an optional method of entry into a dynamic-link library (DLL). If the function is used, it is called by the system when processes and threads are initialized and terminated, or upon calls to LoadLibrary and FreeLibrary.
Syntax
BOOL DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved );
Parameters
HinstDLL
A handle to the DLL. HINSTANCE of a DLL is the same as the HMODULE of the DLL, so hinstDLL can be used in subsequent calls to functions that require a module handle.
fdwReason
Specifies a flag indicating why the DLL entry-point function is being called. This parameter can be one of the following values:
lpvReserved
lpvReserved is NULL.
Return Values
When the system calls DllMain with the DLL_PROCESS_ATTACH value, the function returns:
TRUE if initialization succeeds, FALSE if initialization fails
NOTE: When the system calls DllMain with any value other than DLL_PROCESS_ATTACH, the return value is ignored.
If the return value is FALSE, LoadLibrary returns NULL.
To get extended error information, call GetLastError.
RTSS calls DllMain only for thread-issuing LoadLibrary calls.
On attach, the body of the DLL entry-point function should perform only simple initialization tasks such as creating synchronization objects, and opening files. Do not call LoadLibrary in the entry-point function, because this may create dependency loops in the DLL load order. This can result in a DLL being used before the system has executed its initialization code. Similarly, do not call FreeLibrary in the entry-point function on detach because this can result in a DLL being used after the system has executed its termination code.
Calling Win32 functions other than synchronization, and file functions may result in problems that are difficult to diagnose. For example, calling User, Shell, COM, RPC, and Windows Sockets functions (or any functions that call these functions) can cause access violation errors because their DLLs call LoadLibrary to load other system components.
To provide more complex initialization, create an initialization routine for the DLL and require applications to call the initialization routine before calling any other routines in the DLL. Otherwise, have the initialization routine create a named mutex, and have each routine in the DLL call the initialization routine if the mutex does not exist.