c++ - 如果从 GetProcAddress 获得的函数指针使用 stdlib,程序将崩溃

标签 c++ std loadlibrary

我正在尝试动态加载 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;
}

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

如果我取消注释 std::cout然而,程序在 cout << "Sucessfully loaded myFunc!" << endl; 之后崩溃了行,但在其他任何内容被打印之前。我知道必须有某种方法可以做我想做的事;我需要更改什么才能使其正常工作?

最佳答案

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

关于c++ - 如果从 GetProcAddress 获得的函数指针使用 stdlib,程序将崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50139091/

相关文章:

c++ - GetProcAddress() 失败,错误 127

winapi - 在64位应用程序中加载32位DLL库

c++ - 错误 C2440,战舰 C++

c++ - 对存储在 boost::any 中的 vector 调用 vector::size()

c++ - 为什么QTextDocument背景颜色仅更改一次?

c++ - 为什么 float 参数适合 int 函数参数?

c++ - 需要有关反转输入的递归程序的帮助

c++ - 从列表映射中检索问题

c++ - 可以使用 memset 来填充一组 std::complex<float> 吗?

java - tomcat 7 无法使用 jna 以绝对路径加载我的共享库