从 GetProcAddress 获取的函数指针在使用 stdlib 时会使程序崩溃
Function pointer obtained from GetProcAddress crashes the program if it uses the stdlib
我正在尝试动态加载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
函数的要求暗示我无意中制作了一个巧妙地使用文件扩展名dll
的exe
,而不是实际的dll
(因为我不太了解我正在使用的编译器选项(,这在某种程度上搞砸了该程序集的动态加载。
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- 程序崩溃并显示"std::out_of_range"错误
- CoInitialize()在单独的线程上崩溃而不返回
- 使用调试/崩溃报告将应用程序部署到客户端
- 带有 -stdlib=libc++ 的 clang++ 9.0.1 找不到<optional>
- 为什么所有C++编译器都会崩溃或挂起此代码
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 为什么我的多线程作业队列崩溃
- ExtractIconEx:可以工作,但偶尔会崩溃
- 为什么引用传递会导致此崩溃(C++)
- 试图创建流或fopen时程序崩溃
- 类对象数组的问题会导致崩溃
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 为什么要增加导致崩溃的指针
- 在虚幻引擎中删除NXOpen对象时崩溃
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 从 GetProcAddress 获取的函数指针在使用 stdlib 时会使程序崩溃