开发者

Get Position Of Field In Struct

开发者 https://www.devze.com 2023-01-24 05:02 出处:网络
A fairly simple question (I hope).Given a struct in C (the la开发者_高级运维yout of which is known at compile time), is there a way (via macro, or other) that I can access the byte position of a named

A fairly simple question (I hope). Given a struct in C (the la开发者_高级运维yout of which is known at compile time), is there a way (via macro, or other) that I can access the byte position of a named field in the struct?

Support for unions would be a bonus. The compiler is VC++ 2008. Assume that #pragma pack(1) is used.

Cheers


You're looking for offsetof. It should be in stddef.h, but in case you don't have that, a sample implementation (from wikipedia):

#define offsetof(st, m) \
    ((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))

For a union, the offset of every field is 0.


Use offsetof, from <stddef.h>.

(Unless MSVC++ 2008 doesn't provide it, in which case implement your own as per Carl Norum. I'm pretty sure it's been in since C89, though).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号