我正在尝试构建一个DLL,我后来想使用SetWindowsHookEx()函数注入一些进程.奇怪的是,当我尝试加载DLL并尝试使用GetProcAddress来获取其中包含的过程的地址时,如果我尝试获取CBT消息处理过程的地址,它将返回NULL,但它可以正常工作其他功能.
这是代码.
DLL HEADER(.h)
#include
extern "C" {
__declspec(dllexport) LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam);
__declspec(dllexport) int add(int a, int b);
}
DLL文件(.cpp)
#include "SimpleHook.h"
extern "C" {
__declspec(dllexport) LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam) {
return CallNextHookEx(0, code, wParam, lParam);
}
__declspec(dllexport) int add(int a, int b) {
return a + b;
}
}
主要文件
#include
#include
#include
int main(int argc, char* argv[]) {
HINSTANCE dllHandle = LoadLibrary(_T("SimpleHook.dll"));
if (dllHandle) {
// returns the correct address
cout << "add address: " << GetProcAddress(dllHandle, "add") << endl;
// returns NULL
cout << "hookProc address: " << GetProcAddress(dllHandle, "hookProc") << endl;
}
}
如果我使用GetLastError(),我会得到127错误代码,意思是:
ERROR_PROC_NOT_FOUND: The specified procedure could not be found.
奇怪的是,正确加载了同一文件中的其他函数.
任何帮助是极大的赞赏!
解决方法:
调用约定更改名称mangling. __stdcall函数的名称前面总是_和其他一些方式受到损坏,因此链接失败,但__cdecl函数没有被破坏,所以它被找到了.
要从使用__declspec(dllexport)构建的DLL导入,应始终在要导入的所有内容上包含带__declspec(dllimport)的标头,并链接从构建DLL获得的库.这将保证您的所有功能正确链接,并且您不必进行C兼容链接.
您不应该使用GetProcAddress,也不应该使用外部“C”和__declspec(dllexport).
标题:
#include
#ifndef MAIN
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
DLL_API LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam);
DLL_API int add(int a, int b);
DLL .cpp文件:
#include "SimpleHook.h"
DLL_API LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam) {
return CallNextHookEx(0, code, wParam, lParam);
}
DLL_API int add(int a, int b) {
return a + b;
}
主.cpp文件:
#define MAIN
#include "SimpleHook.h"
int main(int argc, char* argv[]) {
if (dllHandle) {
// returns the correct address
cout << "add address: " << add << endl;
// returns NULL
cout << "hookProc address: " << hookProc << endl;
}
}
不要忘记将lib添加到链接器.
标签:c,dll
来源: https://codeday.me/bug/20190723/1515364.html