如何在dll导出的类中隐藏成员变量 [英] How to hide member variables in a dll-exported class

查看:159
本文介绍了如何在dll导出的类中隐藏成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在dll文件中导出具有1024个字节的类。

I'd like to export a class with 1024 bytes in a dll file.

class __declspec(dllexport) ExportedClass
{
private:
    char Data[1024]; // Holding 1024 bytes.
public:
    void Foo();
};

所以,当我将此类的头文件提供给客户时,
d想隐藏其成员变量char Data [1024](在这种情况下)。

So, when I give this header file of the class to my clients, I'd like to hide its member variable, char Data[1024] in this case.

class __declspec(dllimport) ExportedClass
{
private:
    // char Data[1024]; // You don't have to know.
public:
    void Foo();
};

但是,如果不定义数据,则堆栈内存中不会分配1024个字节,

However without the difinition of the Data, there is no allocation of 1024 bytes in the stack memory, which causes an access violation eventually.

int main()
{
    ExportedClass Obj; // The compiler thinks Obj has no variables to allocate.
    Obj.Foo(); // Crushes because Data points to some invalid space.
    return 0;
}

有没有办法不明确告诉编译器一个类的大小,而是还告诉它表现出来,当您据说必须从dll文件导入一个类时,它应该表现吗?

Is there a way NOT to explicitly tell the compiler the size of a class but also tell it to behave as it should when you supposedly have to import a class from a dll file?

我已经使用Visual Studio 2013 Update 3测试了此代码。

I've tested this code using Visual Studio 2013 Update 3.

谢谢。

推荐答案

如果不想显示成员,则只需创建 Interface 要公开的方法,然后将该接口提供给DLL用户。

If you don't want to show the members, then just create an Interface of the methods you want to expose, and then just give that interface to the DLL user.

您将必须创建 工厂 方法可在dll中创建类,并只返回指向接口的指针。

You will have to create a factory method to create the class inside your dll, and just return a pointer to the interface though.

另一个有趣的事实:如果所有方法都是虚拟的,那么您甚至不必使用declspec导出它们。

虚拟查找表负责提供程序实际指向方法的指针。

Another fun fact: if all the methods are virtual, you don't even have to export them with declspec.
The virtual lookup table takes care of giving the program the actual pointer to the methods.

这篇关于如何在dll导出的类中隐藏成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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