问题描述
您好。我需要在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.
推荐答案
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.
#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 ++中导出类及其派生数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!