从 GetProcAddress 获取的函数指针在使用 stdlib 时会使程序崩溃

Function pointer obtained from GetProcAddress crashes the program if it uses the stdlib

本文关键字:stdlib 崩溃 程序 获取 GetProcAddress 函数 指针      更新时间:2023-10-16

我正在尝试动态加载dll并在运行时从中调用函数。我已经成功地获得了带有GetProcAddress的工作指针,但是如果dll中的函数使用stdlib,程序就会崩溃。以下是加载dll的可执行文件中的代码:

#include <iostream>
#include <windows.h>
typedef int (*myFunc_t)(int);
int main(void) {
using namespace std;
HINSTANCE dll = LoadLibrary("demo.dll");
if (!dll) {
cerr << "Could not load dll 'demo.dll'" << endl;
return 1;
}
myFunc_t myFunc = (myFunc_t) GetProcAddress(dll, "myFunc");
if (!myFunc) {
FreeLibrary(dll);
cerr << "Could not find function 'myFunc'" << endl;
return 1;
}
cout << "Successfully loaded myFunc!" << endl;
cout << myFunc(3) << endl;
cout << myFunc(7) << endl;
cout << myFunc(42) << endl;
cout << "Successfully called myFunc!" << endl;
FreeLibrary(dll);
return 0;
}

以下是实际有效的dll的代码:

#include <iostream>
extern "C" {
__declspec(dllexport) int myFunc(int demo) {
//std::cout << "myFunc(" << demo << ")" << std::endl;
return demo * demo;
}
}
int main(void) {
return 0;
}

(注意,dll代码中的main方法只是为了安抚编译器(

但是,如果我取消注释该行std::cout,则程序会在cout << "Sucessfully loaded myFunc!" << endl;行之后但在打印其他任何内容之前崩溃。我知道一定有办法做我想做的事;我需要更改什么才能使其正常工作?

正如评论中所讨论的,事实证明,编译器对main函数的要求暗示我无意中制作了一个巧妙地使用文件扩展名dllexe,而不是实际的dll(因为我不太了解我正在使用的编译器选项(,这在某种程度上搞砸了该程序集的动态加载。