【发布时间】:2013-07-02 10:31:10
【问题描述】:
我需要在我的其他代码中验证虚拟成员函数的代码。那么如何获得指向正确代码的指针呢?
class MyInterface {
public:
virtual void VirtualMethod() = 0;
};
class MyImplementation : public MyInterface {
private:
int m_value;
public:
MyImplementation() : m_value(0) { }
virtual void VirtualMethod() {
m_value = 1;
}
};
void main(int argc, char* argv[])
{
MyInterface* pInterface = new MyImplementation();
// In my real code on the following line, we do not have access to the declaration of MyImplementation
unsigned int* pFunctionPointer = (unsigned int*)pInterface->VirtualMethod;
// Now we want to access the compiled code of MyImplementation::VirtualMethod.
printf("0x%08x\n", *pFunctionPointer);
}
在我的实际代码中,我根本无法从“main”函数访问 MyImplementation 声明,如果你明白我的意思的话。
【问题讨论】:
-
使用编译器上的-S选项生成汇编输出,并在生成的汇编文件中定位相关函数?
-
啊,对不起,没看到你实际上没有源代码。您必须找到 vtable 并在 vtable 中找到相关地址。不幸的是,这意味着知道该特定函数在 vtable 中具有什么“索引”。另一方面,使用
objdump或dumpbin反汇编包含该函数的目标文件(或dll)可能会更幸运。 -
感谢您的建议。我确实有源文件,但我需要以编程方式查找代码。我正在编写的代码必须检查虚方法中的代码是否符合预期(例如CRC检查)。
-
检查所有代码不是更有意义吗?当然,如果你只检查虚方法,你会在检查后容易受到替代方法的攻击吗?
-
这取决于为什么要检查代码。上面的代码被设置为只提供一个合理的场景。实际的代码是不同的。我仍然需要从其他代码中访问虚拟方法代码。
标签: c++ pointers virtual member