I am learning COM. I wrote a simple COM component in the DLL and registered it in the registry. Then I created a simple client and tried to use my COM component. But I don't understand the DllMain
behaviour (I read this also).
extern "C" BOOL WINAPI DllMain(
_In_ HINSTANCE hinstDLL,
_In_ DWORD fdwReason,
_In_ LPVOID lpvReserved){
pDll = hinstDLL;
if (DLL_PROCESS_ATTACH == fdwReason){
trace("DllMain(): DLL_PROCESS_ATTACH");
}
else if (DLL_THREAD_ATTACH == fdwReason){
trace("DllMain(): DLL_THREAD_ATTACH");
}
else if (DLL_PROCESS_DETACH == fdwReason){
trace("DllMain(): DLL_PROCESS_DETACH");
}
else if (DLL_THREAD_DETACH == fdwReason){
trace("DllMain(): DLL_THREAD_DETACH");
}
else{
trace("DllMain(): unknown variant...");
}
return TRUE;
}
I expected for each DLL_PROCESS_ATTACH
one DLL_PROCESS_DETACH
to be called and for each DLL_THREAD_ATTACH
one DLL_THREAD_DETACH
to be called (if the exception doesn't happen).
But I see for a single DLL_PROCESS_ATTACH
there are two DLL_THREAD_DETACH
:
Why does it happen?
About
DLL_THREAD_ATTACH
:There is no relation between the number of
DLL_THREAD_ATTACH
andDLL_THREAD_DETACH
. It's all about loading and creation time. When a thread is created while a DLL is loaded,DLL_THREAD_ATTACH
will be called. When a thread exits while a DLL is loaded,DLL_THREAD_DETACH
will be called. A thread will never be preempted by a DLL, so the THREAD calls can only happen at creation and end of a thread.In you case, the log only says that you didn't create a thread after loading the DLL, but two thread exited before unloading the DLL.