Access to private class members

I need to access an object from a DLL, perform some manipulations with the object, and pass the object to another function. The problem is that the fields I need to change are private.

I do not want to change the private modifier for the fields of the source class, because the class was written a long time ago and is used in many places. However, in the place where I manipulate the class, I need most of the fields without protection (this is a hack). What is the best way to do this?

Note. I am not allowed to modify the source class

+4
source share
4 answers

If you can see the source class, you can make the mock class with the same bit pattern and pass the source object to an object of class mock

Example below

Original class

class ClassWithHiddenVariables { private: int a; double m; }; 

Mock class

  class ExposeAnotherClass { public: int a_exposed; double m_exposed; }; 

If you want to see members of the ClassWithHiddenVariables object, use reinterpret_cast to transfer to ExposeAnotherClass

  ClassWithHiddenVariables obj; obj.SetVariables(10, 20.02); ExposeAnotherClass *ptrExposedClass; ptrExposedClass = reinterpret_cast<ExposeAnotherClass*>(&obj); cout<<ptrExposedClass->a_exposed<<"\n"<<ptrExposedClass->m_exposed; 
+1
source

What is compiled in the DLL does not really matter in this case, it is important to include the header file . I suggest you change the header file of the class you are interested in so that the variables you need are public .

Member access is checked by the compiler, not the linker, so all that matters is how the class is declared. This does not require you to recompile the DLL or change the implementation of the class, but simply change the header file (or a copy of the header file).

+3
source

One way to do this is to write Getter / Setter functions

+1
source

Hacking "Forger" from C ++ Exclusive Style, clause 15 will work. Although, this is illegal because it violates the rule of one definition, so I would advise against doing so in production code.

From Page 106

 // Example 15-1: Lies and Forgery // class X { // instead of including xh, manually (and illegally) duplicates X's // definition, and adds a line such as: friend ::Hijack( X& ); }; void Hijack( X& x ) { x.private_ = 2; } 

Note that access to the private member of class X "private_" is available in Hijack.

0
source

Source: https://habr.com/ru/post/1393009/


All Articles