代码之家  ›  专栏  ›  技术社区  ›  Matěj Zábský

C++/CLI宏的偏移

  •  2
  • Matěj Zábský  · 技术社区  · 17 年前

    宏的偏移似乎不能在C++/CLI下工作。

    这在非托管C++中是很好的,但是抛出“错误C2255:‘实体’:非法使用这种类型作为表达式CLI中的错误。

    struct Property{
         char* label;
         PropertyTypes type;
         unsigned int member_offset;
         unsigned int position;
         unsigned char bit_offset;
    };
    
    struct Entity{
         ...
         bool transparent;
         ...
    };
    
    Property property = {"Transparent",     
           TYPE_BOOL,       
           offsetof(Entity, transparent), 
           0, 
           0}; // C2275 HERE
    

    cli有替代品吗?

    4 回复  |  直到 16 年前
        1
  •  4
  •   SmoCoder    17 年前

    我猜想编译器消息可以归结为:“offsetof”不是一个已知的宏,如果它是一个函数,则其参数不能包含typename。

    编辑 :正如有人在评论中指出的那样, 抵销 实际上是标准库的一部分。所以缺少的可能只是

    #include <cstddef>
    

    或者,可以使用此宏实现(取自win32/mfc头段):

    #ifdef _WIN64
        #define OFFSET_OF( s, m )\
          (size_t)((ptrdiff_t)&reinterpret_cast<const volatile char&>((((s*)0)->m)) )
    #else
        #define OFFSET_OF( s, m )\
          (size_t)&reinterpret_cast<const volatile char&>((((s*)0)->m))
    #endif
    
        2
  •  1
  •   MSalters    17 年前

    标准C++已经有了替代方案; &Entity::transparent . 重新设计属性类时,您可能需要使用模板。指向成员的指针的类型非常重要。

        3
  •  0
  •   dirkgently    17 年前

    您需要提供要分配给的对象的类型。似乎存在问题成员的某种类型不匹配。

    this 用于样品使用。

        4
  •  0
  •   DevSolar    16 年前

    只是黑暗中的一枪,没有机会再检查一下-应该

    offsetof(Entity, transparent),
    

    也许更适合阅读

     offsetof( struct Entity, transparent ),
    

    ????

    推荐文章