【译】如何从DLL中导出C++类

Important: Marking the class as exported with the __declspec(dllexport) specifier tells the compiler to attempt to export everything that is related to the class. It includes all classdata members, all class member functions (either explicitly declared, or implicitly generated by the compiler), all base classes of the class, and all their members. Consider:

通过 __declspec(dllexport) 导出一个类,是要告诉编译器导出此类相关的一切。包括类的成员变量,成员函数(无论是显式声明的,还是编译器隐式生成的),所有的基类和他们的成员。考虑:

 1 class Base
 2 {
 3     ...
 4 };
 5 
 6 class Data
 7 {
 8     ...
 9 };
10 
11 // MS Visual C++ compiler emits C4275 warning about not exported base class.
12 class __declspec(dllexport) Derived :
13     public Base
14 {
15     ...
16 
17 private:
18     Data m_data;    // C4251 warning about not exported data member.
19 };

In the above code snippet, the compiler will warn you about the not exported base class and the not exported class of the data member. So, in order to export a C++ class successfully, a developer is required to export all the relevant base classes and all the classes that are used for the definition of the data members. This snowball exporting requirement is a significant drawback. That is why, for instance, it is very hard and tiresome to export classes that are derived from STL templates or to use STL templates as data members. An instantiation of an STL container like std::map<>, for example, may require tens of additional internal classes to be exported.

在上面的代码片段中,编译器将会提示你未导出基类和类的成员变量。因此,要成功导出C++类,开发者必须导出所有相关基类和所有成员变量的类。这个滚雪球般的导出需求是一个重要的缺点。这也是为什么导出STL模板类的子类或拥有模板类成员变量的类,是如此困难和烦人。例如一个像std::map<>的STL容器,也许需要导出数十个其他的类。

 

原文:http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL#WhatAboutSTL

posted @ 2012-08-14 09:49  iThinking  阅读(529)  评论(0编辑  收藏  举报