获取C++类中的虚函数表的指针和虚函数表中函数的指针

来源:互联网 发布:在淘宝上买药的流程 编辑:程序博客网 时间:2024/05/16 05:03

通过读内存中类的结构相关信息, 请阅读如下代码:

class CTest
{
public:
 CTest();
 ~CTest();

 virtual void Print();
 virtual void Print2();
 int GetSize();

protected:
private:
 int i;  //在构造函数中初始化 100
 
};

 

#include "Test.h"


typedef void(*FUN)(void); //定义函数的指针

int _tmain(int argc, _TCHAR* argv[])
{
 FUN pFunction = NULL;
 CTest* pTest = new CTest;

 int* pInt = (int*)pTest; // 虚函数表的地址

 int* pFirstVf =  (int*)(*pInt); //虚函数表中的第一虚函数

 pFunction = (FUN)*(pFirstVf); //第一个虚函数
 pFunction();

 pFunction = (FUN)*(pFirstVf + 1); //第二个虚函数
 pFunction();

 int *nInt = pInt +1; // 这是类中虚函数指针后面的一个变量
 getchar();


 return 0;
}