嗨,我遇到了以下问题,我无法弄清楚发生了什么。
DLL 代码 mylib.cpp (mylib.dll):
#include <Windows.h>
#include <tchar.h>
__declspec(dllexport) LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam) {
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserverd){
// Perform actions based on the reason for calling.
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
// Initialize once for each new process.
// Return FALSE to fail DLL load.
MessageBox(NULL,
_T("DLL Loaded"),
_T("DLL Loaded"),
NULL);
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
MessageBox(NULL,
_T("DLL Unloaded"),
_T("DLL Unloaded"),
NULL);
break;
}
return TRUE;
}
程序代码 my_prog.cpp:
#include <Windows.h>
#include <tchar.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){
FARPROC pHookProc;
static HINSTANCE hInstDLL;
hInstDLL = LoadLibrary(_T("mylib.dll"));
pHookProc = GetProcAddress(hInstDLL, "HookProc");
if (!pHookProc) {
MessageBox(NULL,
_T("GetProcAddress failed"),
_T("GetProcAddress failed"),
NULL);
}
return 0;
}
这两个文件都编译没有任何错误。每当我运行 my_prog.exe 时,它会给出一条消息“DLL Loaded”,然后立即给出消息“DLL unloaded”,因此 GetProcAddress() 失败。请有人为我照亮它。为什么它会立即卸载 DLL?
谢谢大家。
编辑:
我已按照c-smile 的建议将 DLL_THREAD_ATTACH 替换为 DLL_PROCESS_DETACH 。我检查并导出函数为:long __stdcall HookProc(int,unsigned int,long) (1)(0x00001000)。GetProcAddress() 仍然失败。我得到“DLL 加载”,GetProcAddress() 失败,“DLL 卸载”