访问类中的私有成员
我需要从 DLL 访问一个对象,对该对象进行一些操作并将该对象提供给另一个函数。问题是我需要更改的字段是私有的。
我不想更改原始类中字段的 private 修饰符,因为该类是很久以前编写的并且在很多地方都使用了。然而,我操作类的地方我需要大多数字段而没有保护(这是一个黑客)。最好的方法是什么?
注意:我不能改变原来的班级
I need to access an object from a DLL, do some manipulations to the object and feed the object to another function. The trouble is the fields I need to change are private.
I don't want to change the private modifier for the fields in the original class because the class was written a long time ago and is used in many places. However, the place where I am manipulating the class I need most of the fields without protection (it is a hack). What is the best way to do it?
Note: I am not allowed to change the original class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下,DLL 中编译的内容并不重要,重要的是您包含的头文件。我建议您更改您感兴趣的类的头文件,以便您需要的变量是
public
。成员访问由编译器而不是链接器检查,因此重要的是类的声明方式。这并不需要您重新编译 DLL 或更改类的实现,而只需修改头文件(或头文件的副本)。
What is compiled in the DLL is not really important in this case, what matters is the header file you include. I suggest you change the header file of the class you're interested in so that the variables you need are
public
.Member access is checked by compiler and not by 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 to just modify the header file (or a copy of the header file).
如果您可以看到原始类,您可以创建一个具有相同位模式的模拟类,并将原始对象强制转换为模拟类对象,
下面的示例
原始类
模拟类
当您想查看 ClassWithHiddenVariables 对象的成员时,请使用reinterpret_cast 强制转换为暴露另一个类
If you can see the original class you can make a mock class with the same bit pattern and cast the original object to the mock class object
Example below
Original class
Mock class
When you want to see members of the ClassWithHiddenVariables object, use reinterpret_cast to cast to ExposeAnotherClass
一种方法:编写 Getter / Setter 函数
One way to do it: Write Getter / Setter functions
来自Exceptional C++ Style,Item 15的“Forger” hack 将会起作用。尽管如此,它是非法的,因为它违反了“单一定义规则”,所以我建议不要在生产代码中这样做。
从第 106 页开始,
请注意如何在 Hijack 中访问类 X 的私有成员“private_”。
The "Forger" hack from Exceptional C++ Style, Item 15 will work. Although, it is illegal as it violates the One Definition Rule so I'd advise against doing this in production code.
From page 106
Note how class X's private member "private_" is accessible in Hijack.