无法理解宏定义(将常量数强制转换为类指针)

can't understand a macro definition (casting constant number to a class pointer)

本文关键字:转换 指针 常量 宏定义      更新时间:2023-10-16

在代码中,我看到下面定义的宏,我无法理解。

#define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>(      
  &reinterpret_cast<NetParameter*>(16)->f) - 
   reinterpret_cast<char*>(16))

宏名称似乎正在计算类结构内字段 f 的偏移量。 它具有从字段地址中减去起始地址的形式。这里如何使用数字 16?Deosn reinterpret_case只适用于16吗?(不是 16 -> f)。如果有人请向我解释此代码,我将不胜感激。

(现已重构)protobuf 标头中的注释(此处链接)对此进行了解释

// Note that we calculate relative to the pointer value 16 here since if we
// just use zero, GCC complains about dereferencing a NULL pointer.  We
// choose 16 rather than some other number just in case the compiler would
// be confused by an unaligned pointer.
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD)    
  static_cast<int>(                                           
      reinterpret_cast<const char*>(                          
          &reinterpret_cast<const TYPE*>(16)->FIELD) -        
      reinterpret_cast<const char*>(16))
#endif

因此,使用16的原因有两个:

  • 避免使用 NULL 指针
  • 使用对齐的指针

请注意,已知这会产生一些问题(如果支持,可能会替换为__builtin_offsetof)。