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).
精彩评论