问题描述
我正在编写一个定义全局静态对象的DLL。
在对象的构造函数中,我正在做一些可能成功或可能不会成功的初始化。
是否可以在DllMain()中发出初始化过程的成功或失败?
谢谢。
MSDN的文档说:
由于DllMain中的代码可能使用静态对象,所以静态对象必须在DllMain运行DLL_PROCESS_ATTACH前构建,并在运行DLL_PROCESS_DETACH后被销毁。
您可以使用简单的测试exe和测试dll验证这一点。
EXE:
int _tmain(int argc,_TCHAR * argv [])
{
wprintf(LMain,loading library\\\
);
HMODULE h = LoadLibrary(LTest.dll);
if(h)
{
wprintf(LMain,freeing library\\\
);
FreeLibrary(h);
}
wprintf(LMain,exiting\\\
);
return 0;
}
DLL:
struct Moo
{
Moo(){wprintf(LMoo,constructor\\\
); }
〜Moo(){wprintf(LMoo,destructor\\\
); }
};
Moo m;
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch(ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
wprintf(LDllMain,DLL_PROCESS_ATTACH\\\
);
break;
case DLL_THREAD_ATTACH:
wprintf(LDllMain,DLL_THREAD_ATTACH\\\
);
break;
case DLL_THREAD_DETACH:
wprintf(LDllMain,DLL_THREAD_DETACH\\\
);
break;
case DLL_PROCESS_DETACH:
wprintf(LDllMain,DLL_PROCESS_DETACH\\\
);
break;
default:
wprintf(LDllMain,???? \\\
);
break;
}
return TRUE;
}
这些将打印出来:
主要,加载库
Moo,构造函数
DllMain,DLL_PROCESS_ATTACH
主要,释放库
DllMain,DLL_PROCESS_DETACH
Moo,析构函数
主,退出
如您所见,静态对象是在 DllMain(...,DLL_PROCESS_DATACH,...)
并在 DllMain(...,DLL_PROCESS_DETACH,...)之后销毁$ c>
I am writing a DLL which defines a global static object.
In the object's constructor I am doing some initialization that may or may not succeed.
Is it possible to signal success or failure of the initialization process in DllMain() ? Which of the two is called first ?
Thank you.
MSDN's DllMain documentation says:
Since the code within DllMain may use the static objects, the static objects must be constructed before DllMain is run for DLL_PROCESS_ATTACH, and destroyed after it is run for DLL_PROCESS_DETACH.
You can verify this with a simple test exe and test dll.
EXE:
int _tmain(int argc, _TCHAR* argv[])
{
wprintf(L"Main, loading library\n");
HMODULE h = LoadLibrary(L"Test.dll");
if (h)
{
wprintf(L"Main, freeing library\n");
FreeLibrary(h);
}
wprintf(L"Main, exiting\n");
return 0;
}
DLL:
struct Moo
{
Moo() { wprintf(L"Moo, constructor\n"); }
~Moo() { wprintf(L"Moo, destructor\n"); }
};
Moo m;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
wprintf(L"DllMain, DLL_PROCESS_ATTACH\n");
break;
case DLL_THREAD_ATTACH:
wprintf(L"DllMain, DLL_THREAD_ATTACH\n");
break;
case DLL_THREAD_DETACH:
wprintf(L"DllMain, DLL_THREAD_DETACH\n");
break;
case DLL_PROCESS_DETACH:
wprintf(L"DllMain, DLL_PROCESS_DETACH\n");
break;
default:
wprintf(L"DllMain, ????\n");
break;
}
return TRUE;
}
Together those will print:
Main, loading library
Moo, constructor
DllMain, DLL_PROCESS_ATTACH
Main, freeing library
DllMain, DLL_PROCESS_DETACH
Moo, destructor
Main, exiting
As you can see, the static object is constructed before DllMain(...,DLL_PROCESS_ATTACH,...)
and destroyed after DllMain(...,DLL_PROCESS_DETACH,...)
这篇关于哪个叫第一,DllMain()或全局静态对象构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!