我正在尝试从控制台编译DLL,而不使用任何IDE并遇到下一个错误。
我写了这段代码:
test_dll.cpp
#include <windows.h>
#define DLL_EI __declspec(dllexport)
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, LPVOID lpvReserved){
return 1;
}
extern "C" int DLL_EI func (int a, int b){
return a + b;
}
然后使用命令icl /LD test_dll.cpp
进行编译。我试图从另一个程序中调用func
:
prog.cpp
int main(){
HMODULE hLib;
hLib = LoadLibrary("test_dll.dll");
double (*pFunction)(int a, int b);
(FARPROC &)pFunction = GetProcAddress(hLib, "Function");
printf("begin\n");
Rss = pFunction(1, 2);
}
使用icl prog.cpp
进行编译。然后我运行它,它失败了标准窗口“程序不工作”。可能存在分段错误错误。
我做错了什么?
答案 0 :(得分:3)
检查LoadLibrary()
和GetProcAddress()
是否都成功,在这种情况下,它们肯定不会被导出的函数调用func
,而不是"Function"
,如参数中指定的那样GetProcAddress()
表示在尝试调用它时,函数指针将为NULL
。
函数指针的签名也与导出函数的签名不匹配,导出的函数返回int
,函数指针期望double
。
例如:
typedef int (*func_t)(int, int);
HMODULE hLib = LoadLibrary("test_dll.dll");
if (hLib)
{
func_t pFunction = (func_t)GetProcAddress(hLib, "func");
if (pFunction)
{
Rss = pFunction(1, 2);
}
else
{
// Check GetLastError() to determine
// reason for failure.
}
FreeLibrary(hLib);
}
else
{
// Check GetLastError() to determine
// reason for failure.
}