c++ - 显式链接 DLL 和类方法

标签 c++ visual-studio dll

我想通过创建一个 DLL 并将其导入到我的主程序中来制作一个动态库。 但是我无法正确运行我的程序,因为我从 LIB 切换到 DLL。

这是我的 DLL .h 文件:

class Connector
{
public:
    Connector(std::string _apiKey, 
              std::string _masterCode,
              std::string _masterSystem, 
              std::string _masterVersion, 
              int INTERNAL_PARAMETER = -1);
    virtual ~Connector();
    std::string query(std::string method, 
                      std::map<std::string, 
                      std::string> params);
    [...]
}

这是我的 mainApp 中的链接代码:

typedef std::string (CALLBACK* kcDLLFUNC_QUERY)(
         std::string, std::map<std::string, std::string>, std::string);

HINSTANCE kcDLL = LoadLibrary(_T("Connect"));
kcDLLFUNC_QUERY kcDLLFUNC_query = (kcDLLFUNC_QUERY)GetProcAddress(kcDLL, "query");

std::map<std::string, std::string> params;
params["amount"] = "50";
std::string RES = kcDLLFUNC_query("de", params, "");
std::cout << RES << std::endl;
FreeLibrary(kcDLL);

我是不是忘记了什么?

最佳答案

主要问题是 GetProcAddress() 仅适用于 extern "C" 函数。您要调用的函数是一个类的成员,并且您没有导出该函数或整个类。

我通常通过向 DLL 项目添加一个定义来实现这一点,然后在 DLL 项目中创建一个 header ,该 header 定义一个指示函数/类是导出还是导入的宏。像这样:

// Assumes IS_DLL is defined somewhere in the project for your DLL
// (such as in the project's Properties: C/C++ -> Preprocessor)
#ifdef IS_DLL
    #define DLL_API __declspec(dllexport)
#else
    #define DLL_API __declspec(dllimport)
#endif

然后像这样修改你的类:

#include "DllExport.h" // name of the header file defined above

class DLL_API Connector
{
public:
    Connector(std::string _apiKey, std::string _masterCode, std::string _masterSystem, std::string _masterVersion, int INTERNAL_PARAMETER = -1);
    virtual ~Connector();
    std::string query(std::string method, std::map<std::string, std::string> params);
    [...]
}

在您的 .exe 中,包含您的类的 header ,并照常使用它。您还需要链接到 DLL。在最新版本的 Visual Studio 中,这是按如下方式完成的:

  1. 在解决方案资源管理器中,展开 .exe 项目。
  2. 右键单击References,然后选择Add Reference...
  3. 在对话框中,选择左侧列表中的解决方案
  4. 选中 DLL 项目旁边的复选框,然后按“确定”。

如果您最终为您的程序创建了多个 DLL,则需要更改定义的名称以免它们发生冲突(我通常在每个定义的名称中包含 DLL 的名称)。

关于c++ - 显式链接 DLL 和类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44566955/

相关文章:

c++ - 为什么自由函数和成员函数都存在用于比较和交换操作?

C++11、shared_ptr.reset() 和循环引用

c++ - 如何在同一个程序中创建多个套接字。?

visual-studio - 如何在 Visual Studio 2008 中为源代码管理命令分配键盘快捷键?

C# dll 求解简单方程

发布表单但丢失参数

c++ - 两个线程可以调用同一个 DLL 中的两个函数吗?

c++ - 数组索引循环开始而不是内存访问错误

visual-studio - Visual Studio 团队套件

visual-studio - Visual Studio - 构建后事件 - 抛出错误