How to hide member variables in a dll-exported class

孤者浪人 提交于 2020-05-13 18:14:54

问题


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();
};

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();
};

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;
}

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?

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

Thanks in adavance.


回答1:


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.

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

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.



来源:https://stackoverflow.com/questions/25830791/how-to-hide-member-variables-in-a-dll-exported-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!