问题
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