C++ reinterpret_cast 一个整数

标签 c++ pointers reinterpret-cast offsetof

我遇到了以下 C++ 代码:

 #define OFFSETOF_MEMBER(t, f) \
  (reinterpret_cast<uintptr_t>(&reinterpret_cast<t*>(16)->f) - static_cast<uintptr_t>(16u)) // NOLINT

其中 t 是类型,f 是字段名。我想知道为什么我们可以把一个整数 16 作为 reinterpret_cast 的参数。

最佳答案

16 是我们分配给指针的地址,它让我们计算指定成员的偏移量。指针的地址只是一个数字,因此我们可以滥用这一事实来获取有关我们的结构/类的信息。

假设我们有一个结构:

struct point { 
    //Assuming 32-bit integer sizes. 
    //For 64-bit integersizes, 0x0, 0x8, 0x10 for the integer offsets
    int x; //Offset 0x0
    int y; //Offset 0x4
    int z; //Offset 0x8
}; static_assert(sizeof(point) == 12 /* or 0xC in hex */);

我们使用宏:

OFFSETOF_MEMBER(point, y);

展开宏,我们得到:

(reinterpret_cast<uintptr_t>(&reinterpret_cast<point*>(16)->y) - static_cast<uintptr_t>(16u)

另一种表达 reinterpret_cast<point*>(16)->y 的方式可以这样:point * myPt = 16u;我们知道 16 不是一个有效地址,但编译器不知道,只要我们不尝试读取我们指向的地址,就没问题。

接下来,我们可以简化所有&reinterpret_cast<point*>(16)->y至:&myPt->y .我们从上面知道 y 是 @offset 0x4,并且因为 myPt 是 16:16 + 0x4 = 20

然后我们有reinterpret_cast<uintptr_t>(20u) - static_cast<uintptr_t(16u)20 - 16 ,它给了我们 y 的偏移量,即 0x4。

关于C++ reinterpret_cast 一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51395044/

相关文章:

c++ - CPP 错误: "called object type ' int (hashTable::*)(int, int )' is not a function or function pointer"

c++ - 在 void 指针中存储整数的往返安全性

c - 如何在 C 中正确释放 char**

c++ - 重新诠释

c++ - 从指向具有相同签名的函数的指针转换为函数指针,但参数的附加限定除外

c++ - 两个相互引用的类

c++ - 获取文件内容并将其放入 C++ 中的字符串中

c++ - LINUX/C++ 从第二个文件中删除第一个文件中的字符串

c++ - 查找 zlib 压缩流的结尾

c - 将 char * 类型转换为 int *