部分dll有时需要在进程中永久有效,如hook, 正常的dll在程序退出时会释放dll, 然后导致dll中的对象被释放(CRT清理)
跟踪源码, 可以看到 在__DllMainCRTStartup 中有调用 _CRT_INIT释放资源,
中间不可控, 但是有一个异常捕获, 尝试生成一个异常, 但是简单异常的过滤条件无法满足
改用自定义入口:
#define _DECL_DLLMAIN
#include <process.h>
#pragma comment(linker, "/ENTRY:DllMainCRTStartup")
extern "C" BOOL WINAPI DllMainCRTStartup(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
BOOL bRetVal;
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
bRetVal = _CRT_INIT(hinstDLL, fdwReason, lpReserved);
HookMgr.Init();
break;
case DLL_THREAD_ATTACH:
bRetVal = _CRT_INIT(hinstDLL, fdwReason, lpReserved);
break;
case DLL_PROCESS_DETACH:
bRetVal = HookMgr.Stop();
if(bRetVal == FALSE)
return FALSE;
bRetVal = _CRT_INIT(hinstDLL, fdwReason, lpReserved);
break;
case DLL_THREAD_DETACH:
bRetVal = _CRT_INIT(hinstDLL, fdwReason, lpReserved);
break;
default:
return TRUE;
}
return bRetVal;
}
其他:
- dll导出 (x86, x64符号命名差异)
pragma comment(linker, "/EXPORT:NsiRpcSetParameterEx=_NopSub@40,PRIVATE")
// x64
pragma comment(linker, "/EXPORT:NsiRpcSetParameterEx=NopSub,PRIVATE")
- dll导出序号