如何从 dll 导出 C++ 类?

2021-12-22 00:00:00 dll visual-c++ c++

我有一个有两个重载函数的类.如何从 dll 导出它以及如何由其他 C++ 类使用它?我的班级看起来像这样:

I have a class which has two overloaded functions. How do I export it from a dll and also how to use it by other C++ classes? My class looks like this:

#define DECLDIREXP __declspec(dllexport) 

#define DECLDIRIMP __declspec(dllimport)


class DECLDIREXP xyz 

{

public: 
          void printing();
          void printing(int a);
};  

using namespace std; 

void xyz::printing()
{
        cout<<"hello i donot take any argument";
}


void xyz::printing(int a)
{
        cout<<"hello i take "<< a <<"as argument";
}

推荐答案

一个常见的方法是有一个单独的宏(我们称之为 EXPORT),它可以扩展为 dllimportdllexport 取决于是否设置了某种立即构建 DLL"定义,如下所示:

A common approach is to have a single macro (let's call it EXPORT) which either expands to dllimport or dllexport depending on whether some sort of "building the DLL right now" define is set, like this:

#ifdef MAKEDLL
#  define EXPORT __declspec(dllexport)
#else
#  define EXPORT __declspec(dllimport)
#endif

class EXPORT xyz {
  // ...
};

这个想法是在构建 DLL 时,将 MAKEDLL 添加到预处理器定义中.这样,所有代码都将被导出.链接到您的 DLL(并因此包含此头文件)的客户端根本不需要做任何事情.通过不定义MAKEDLL,它们将自动导入所有代码.

The idea is that when building your DLL, you add MAKEDLL to the preprocessor definitions. That way, all the code will be exported. Clients who link against your DLL (and hence include this header file) don't need to do anything at all. By not defining MAKEDLL, they will automatically import all the code.

这种方法的优点是正确使用宏的负担从许多(客户端)转移到了 DLL 的作者身上.

The advantage of this approach is that the burden of getting the macros right is moved from the many (the clients) to just the author of the DLL.

这样做的缺点是,当按原样使用上面的代码时,不再可能直接将代码编译到某个客户端模块中,因为不可能将 EXPORT 宏定义为空.为此,您需要进行另一项检查,如果为真,则将 EXPORT 定义为空.

The disadvantage of this is that when using the code above as it is, it's no longer possible to just compile the code directly into some client module since it's not possible to define the EXPORT macro to nothing. To achieve that, you'd need to have another check which, if true, defines EXPORT to nothing.

关于稍微不同的主题:在许多情况下,不可能(或不希望!)像这样导出一个完整的类.相反,您可能只想导出所需的符号.例如,在您的情况下,您可能只想导出两个公共方法.这样,所有私有/受保护成员都不会被导出:

On a slightly different topic: in many cases, it's not possible (or desired!) to export a complete class like that. Instead, you may want to just export the symbols you need. For instance, in your case, you may want to just export the two public methods. That way, all the private/protected members won't be exported:

class xyz
{
public: 
    EXPORT void printing();
    EXPORT void printing(int a);
};

相关文章