如何处理警告:从较小的整数类型int转换为int*

How to process the warning:cast to int* from smaller integer type int

本文关键字:int 整数 类型 转换 何处理 处理 警告      更新时间:2023-10-16

我有一个基类如下:

class Base{ public: virtual void f() { cout << "Base::f" << endl; } };

void testVTable(){
    typedef void (*Func)(void);
    Base b;
    Func pFunc = NULL;
    cout<<"vtable address:"<<(int*)(&b)<<endl;
    cout<<"virtual function address:"<<(int*)*(int*)(&b)<<endl;
    pFunc = (Func)(int*)*(int*)((&b)+0);
    pFunc();}

我想通过在虚拟表中使用 f 的地址来执行函数f()。但是,在MacOS中,该程序在Windows 7中正常运行时崩溃了。我知道int *是 8 个字节,int是 4 个字节,我尝试使用 size_t 替换int,但没有用。我没有办法让它工作。有人可以帮助我吗?

即使您设法在 vtable 中找到正确的函数指针偏移量(这是另一个任务),存储在那里的函数指针也绝对不是常规函数指针。此外,它也可能不是非静态成员函数指针,因此它不起作用。

试试这个:

void testVTable(){
    typedef void (*Func)(void*);
    Base b;
    size_t vtblAddress = *(size_t*)&b;
    Func pFunc = (Func)(*(size_t*)(vtblAddress));
    pFunc(&b);
}

通过使用vs2015进行调试,我终于发现了我的代码有问题,下面是可以在vc6,vs2015和Xcode上正常运行的代码。

void testVTable(){
    typedef void (*Func)(void);
    Base b;
    Func pFunc = NULL;
    cout<<"vtable address:"<<(size_t*)(&b)<<endl;
    cout<<"virtual function address:"<<(size_t*)*(size_t*)*(size_t*)(&b)<<endl;
    pFunc = (Func)(size_t*)*(size_t*)*(size_t*)((&b)+0);
    pFunc();}
相关文章: