在C ++中导出类及其派生数据成员 [英] Exporting a class and its derived data members in C++

查看:95
本文介绍了在C ++中导出类及其派生数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我需要在C ++中导出一个我写过的类。它不是一个子类,因此它不必与其超类一起导出,但它具有从各种DLL派生的数据成员和函数,如setupapi.dll,user32.dll,MPUSBAPI.dll。我是否也需要出口它们?如果是这样,怎么样?在此先感谢。

Hi. I need to export a class in C++ dll i''ve written. It isn''t a subclass so it doesn''t have to be exported along with its superclasses but it has data members and functions derived from various DLL such as setupapi.dll, user32.dll, MPUSBAPI.dll. Do i need to export them too or not? If so, how? Thanks in advance.

推荐答案

不,您只需要导出您班级用户需要导入的成员。 br $> b $ b

另请参阅演练:创建和使用动态链接库(C ++) [ ^ ]
No, you just need to export the members that will need to be imported by users of your class.

See also Walkthrough: Creating and Using a Dynamic Link Library (C++)[^]


您不需要导出数据成员(事实上,如果您导出该类,则无法导出其成员)。但是,客户端代码(在另一端导入的位)需要了解接口上使用的所有类型,因此需要包含标题,例如: windows.h 定义它们。



要非常小心区分导出类定义

You don''t need to export the data members ( In fact if you export the class you can''t export its members ). However the client code ( the bit that''s importing on the other side ) needs to understand all the types used on the interface so it will need to include the headers e.g. windows.h that define them.

Be very careful to distinguish between exporting the class definition
class /*__declspec( dllexport/dllimport )*/ MY_API CMyClass
{
//...
};



并导出该类的实例


and exporting an instance of the class

extern MY_API CMyClass AnInstance;



首先允许客户端代码创建自己的CMyClass实例,第二个用于查看DLL在模块范围内提供的单个实例。

如果有疑问,请使用第一种技术。

另一件事:导出的类中没有任何公共数据成员。使用访问器函数获取,设置。它更便携,更安全,特别是当DLL可以拥有自己的堆并进行自己的内存管理时。


The first allows the client code to create its own instance of CMyClass, the second to see a single instance provided at module scope by the DLL.
If in doubt use the first technique.
One other thing: Don''t have any public data members in the exported class. Use accessor functions Get, Set. It''s more portable and safer that way especially when DLLs can have their own heaps and do their own memory management.


虽然Matthew涵盖了你需要注意的大部分内容,如果你没有保护它,有一件事可能会让你失望,那就是成员的对齐。

看看#pragma pack [ ^ ]



在你的标题中:

While Matthew covered most of the stuff you need to be aware of, there is one thing that may trip you up if you don''t protect against it, and that''s member alignment.
Have a look at #pragma pack[^]

In you header:
#ifndef __MYHEADER_H__
#define __MYHEADER_H__

#pragma pack(push,8) 

class MyClass
{
  char b;
  long long ll;
  bool b2; 
public:


  inline char getb() const { return b; }
  inline long long getll() const { return ll; }
};

#pragma pack(pop)



如果客户端代码使用不同的对齐方式而不是使用#pragma pack编译的代码,则确保内存对齐保持不变正如预期的那样。



祝你好运

Espen Harlinn


If client code uses a different alignment than your code was compiled with #pragma pack ensures that memory alignment stays as expected for your code.

Best regards
Espen Harlinn


这篇关于在C ++中导出类及其派生数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆