2

offsetof 宏似乎在 C++/CLI 下不起作用。

这在非托管 C++ 中运行良好,但在 CLI 中引发“错误 C2275: 'Entity' :illegal use of this type as an expression”错误。

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

4 回答 4

4

我的猜测是编译器消息归结为:“offsetof”不是一个已知的宏,如果它是一个函数,它的参数不能包含类型名。

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

#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
于 2009-03-26T10:48:13.503 回答
1

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

于 2009-03-26T10:46:48.640 回答
0

您需要提供要分配的对象的类型。看起来有问题的成员存在一些类型不匹配。

有关示例用法,请参阅

于 2009-03-25T21:17:44.840 回答
0

只是在黑暗中拍摄,没有机会仔细检查 - 应该

offsetof(Entity, transparent),

也许宁愿读

 offsetof( struct Entity, transparent ),

???

于 2009-03-26T10:29:15.313 回答