如何处理警告:从较小的整数类型int转换为int*
How to process the warning:cast to int* from smaller integer type int
我有一个基类如下:
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();}
相关文章:
- 整数区间(或 int 数组)中每个数字的出现次数
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 如何解决隐式转换丢失整数精度:'size_t'(又名"无符号长")到'int'警告?
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 比较两个整数在C++中与未知 int 类型的相等性
- 创建<int>对整数数组指针的矢量引用 (C++)
- 运行时错误:有符号整数溢出:964632435 * 10 无法在类型 'int' 中表示
- 有什么区别 - 常量 int x = 5000;和常量整数 x = 50'00;在C++?
- 调用 Parse int 函数时编译 parse 整数程序时出现问题
- 尝试使用 Array 类的模板构造整数数组时,错误:为什么数组类型"int [5]"不可分配,
- 如何对 int 变量应用验证,使其仅接受整数数据,并且在任何其他数据的情况下不会出错?
- 错误:调用'begin(long double [nPoints])'没有匹配函数;使用硬编码的 int 与整数变量初始化向量
- 如何将私有整数从A类传递到C 类B类的另一个INT变量
- 在 C++ 中,当我声明一个整数变量 int a = 200L 或 int a = 200F 或 int a = 200
- 我们是否需要担心 32 位或 64 位整数,或者我们只使用 'int'
- 为什么可以将Char指针变量初始化为字符串,而INT指针变量不能初始化到整数数组
- 当我<int>推送包含整数的字符串时,如何修复被推回向量的垃圾值
- 为什么所有可能的整数都"true"在 C++ 的 if 语句内的 long int 范围内,而 0 不是?
- typedef int -> 整数。我可以在 c++ 中执行 cout-> 打印吗?