Balon白话MSDN:从普通DLL中导出C++类(1) – dllexport和dllimport的使用方法(中英对照、附注解)

 
Balon白话MSDN:从普通DLL中导出C++类(1) – dllexport和dllimport的使用方法(中英对照、附注解)
这几天写几个小程序练手,在准备将一个类导出时,发现还真不知道如果不用MFC的扩展DLL,是怎么导出的。但我知道dllexport可以导出函数和变量,而且MFC扩展DLL就算是使用了MFC的功能,但能否导出类应该也不是必须用MFC才能够做到,一定是有相应的机制可以实现。于是查了一下MSDN,发现这个机制简单的可怕,原来就和导出函数一样,把dllexport关键字加到类名前就可以了。估计和我一样的同学大有人在,把MSDN的相关文档翻译出来,附上我的注解,希望对大家有用。
评注程序均在Visual Studio.NET 2005 Professional中测试以得到结果,给出的代码均省略了大量语句,只保留了与主题最相关的部分,因此可能无法编译。
MSDN文档选自2007年4月更新的MSDN Library。
Using dllimport and dllexport in C++ Classes
C++ 类中使用 dllimport dllexport
Microsoft Specific
You can declare C++ classes with the dllimport or dllexport attribute. These forms imply that the entire class is imported or exported. Classes exported this way are called exportable classes.
The following example defines an exportable class. All its member functions and static data are exported:
可以在声明C++类时使用dllimportdllexport属性。这两个形式将隐含导入或导入整个类。通过这种方法导出的类称为可导出类。
下列范例定义了一个可导出类,其所有的成员函数和静态将被导出:

#define  DllExport   __declspec( dllexport )
 
class  DllExport C {
   
int  i;
   
virtual   int  func(  void  ) {  return   1 ; }
};
 
Note that explicit use of the dllimport and dllexport attributes on members of an exportable class is prohibited.
注意,禁止在一个可导出类的成员上显式的使用dllimportdllexport属性。
balon 注:如你不能像下例这样写:
#define  DllExport   __declspec( dllexport )
 
class  DllExport C {
   DllExport 
int  i;     //  不可以在成员上使用dllexport
   DllExport  int  func(  void  ) {  return   1 ; }  //  不可以在成员上使用dllexport
};
 
 
通过dllexport导出类
When you declare a class dllexport, all its member functions and static data members are exported. You must provide the definitions of all such members in the same program. Otherwise, a linker error is generated. The one exception to this rule applies to pure virtual functions, for which you need not provide explicit definitions. However, because a destructor for an abstract class is always called by the destructor for the base class, pure virtual destructors must always provide a definition. Note that these rules are the same for nonexportable classes.
If you export data of class type or functions that return classes, be sure to export the class.
当你声明一个类为dllexport,其所有的成员函数和静态数据成员将被导出。你必须在同一个程序中定义所有此类成员,否则会产生一个链接错误。
balon 注:如在下面的导出类中,func必须在这个DLL的工程中或是在使用DLL的程序中被定义,否则在使用时会出现无法解析的外部符号的链接错误。注意,定义可以放在DLL中,也可放在DLL的使用者工程中,只要在使用前被定义就可以。
方法一:在Dll工程中定义,在使用者工程中直接使用。
//  dll.h
#define  DllExport   __declspec( dllexport )
class  DllExport C {
    
int  func(  void  );
};
 
//  dll.cpp
int  C::func( void )
{
    
  • 1
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值