GetProcAddress函数返回NULL

siv*_*an1 1 c++ windows dll getprocaddress

我试图动态加载C++ DLL,首先我使用"LoadLibrary"函数加载dll并正确处理它的句柄.之后我尝试使用"GetProcAddress"获取DLL文件函数的函数指针,它返回NULL.请找到我的DLL代码并测试应用程序代码,并告诉我代码中出错的地方.

dummy2.h

namespace newer
{
  class dllclass
  {
    public:
        static __declspec(dllexport) int run(int a,int b);
  };
}
Run Code Online (Sandbox Code Playgroud)

dummy2.cpp

#include <iostream>
using namespace std;

#include "dummy2.h"

namespace newer
{
  int dllclass::run(int a,int b)
  {
    return a+b;
  }
}
Run Code Online (Sandbox Code Playgroud)

dummy1.cpp

#include "stdafx.h" 
#include <windows.h>

#include <iostream>
using namespace std;
typedef int (*Addition)(int,int);

int _tmain(int argc, _TCHAR* argv[])
{
  Addition add;
  HINSTANCE hDLL;
  hDLL = LoadLibrary(TEXT("Dummy2.dll"));

  add = (Addition)GetProcAddress(hDLL, "run");  

  getchar();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

请参考上面的代码并指导我.

axa*_*lis 5

这是因为名称被破坏了(即函数的名称不是"运行",而是不同的名称).

您的代码可以使用(对于我测试过的MSVC 2013):

add = (Addition)GetProcAddress(hDLL, "?run@dllclass@newer@@SAHHH@Z");
cout << add(1, 2) << endl;
Run Code Online (Sandbox Code Playgroud)

通常,如果要通过插件加载类,最好的方法是使用虚拟接口.一个例子:

//dummy2.h
namespace newer
{
  class dllclass_interface
  {
    public:
        virtual int run(int a,int b) = 0;
 };

}

extern "C" __declspec(dllexport) newer::dllclass_interface* getDllClass();
Run Code Online (Sandbox Code Playgroud)
//dummy2.cpp
#include <iostream>
using namespace std;

#include "dummy2.h"

namespace newer
{
  class dllclass: public dllclass_interface
  {
    public:
        virtual int run(int a,int b);
 };

  int dllclass::run(int a,int b)
  {
    return a+b;
  }
}

extern "C" newer::dllclass_interface* getDllClass()
{
    static newer::dllclass instance;
    return &instance;
}
Run Code Online (Sandbox Code Playgroud)
typedef newer::dllclass_interface* (*GetClassFunc)();

GetClassFunc getClassFunc = (GetClassFunc)GetProcAddress(hDLL, "getDllClass");

newer::dllclass_interface* dllClass = getClassFunc();
cout << dllClass->run(a, b) << endl;
Run Code Online (Sandbox Code Playgroud)