0

在像 C# 这样的语言中。你可以把public或者internal放在一个类的前面来控制一个类的访问级别。这是如何在 C++ DLL 中完成的?

4

3 回答 3

1

大概您基本上是在询问如何从 DLL 中导出类。

在这种情况下,大多数 Windows 编译器(例如 VC++、MinGW)都使用它__declspec(dllexport)来完成这项工作。

为了反映这一点,客户端代码需要将类声明为__declspec(dllimport). 通常你会得到类似的东西:

#ifdef BUILD_DLL
#define DLL __declspec(dllexport)
#else
#define DLL __declspec(dllimport)
#endif

DLL class whatever { 
    // ...
};

...在标题中,用于构建 DLL 的 make 文件将定义BUILD_DLL

cflags += /DBUILD_DLL
于 2013-09-10T18:17:07.297 回答
0

与 C#(或任何其他现代语言)不同,C++ 语言标准没有谈论动态库/共享对象。

因此,语言/编译器实现者定义自己的跨 DLL/SO 导出类定义的方式都是特定于语言/编译器的。

有关更多信息,请参阅http://gcc.gnu.org/wiki/Visibility

#if defined _WIN32 || defined __CYGWIN__
  #ifdef BUILDING_DLL
    #ifdef __GNUC__
      #define DLL_PUBLIC __attribute__ ((dllexport))
    #else
      #define DLL_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax.
    #endif
  #else
    #ifdef __GNUC__
      #define DLL_PUBLIC __attribute__ ((dllimport))
    #else
      #define DLL_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax.
    #endif
  #endif
  #define DLL_LOCAL
#else
  #if __GNUC__ >= 4
    #define DLL_PUBLIC __attribute__ ((visibility ("default")))
    #define DLL_LOCAL  __attribute__ ((visibility ("hidden")))
  #else
    #define DLL_PUBLIC
    #define DLL_LOCAL
  #endif
#endif

extern "C" DLL_PUBLIC void function(int a);
class DLL_PUBLIC SomeClass
{
   int c;
   DLL_LOCAL void privateMethod();  // Only for use within this DSO
public:
   Person(int _c) : c(_c) { }
   static void foo(int a);
}; 

从上面的代码片段中,您可以观察到导出类直接依赖于编译器特定的扩展。

CL/MSVC - __declspec(dllexport), __declspec(dllimport
GCC - __attribute__ ((visibility ("default")))

GCC 还提供 **-fvisibility=[hidden|default] 以更好地控制通过 DLL/SO 导出的符号。

于 2013-09-10T18:44:30.360 回答
0

通过将一个类嵌套在另一个类中:

class A
{
public:
    class B {};
protected:
    class C {};
private:
    class D {};
};
于 2013-09-10T18:06:14.873 回答