C 结构体嵌入联合中的成员对齐
我正在修改一些 C 代码,大致如下:
typedef struct STRUCT_FOO {
ULONG FooInfo;
union {
ULONG LongData;
USHORT ShortData;
UCHAR CharData;
};
} FOO;
...
FOO foo;
ULONG dataLength = offsetof(FOO, CharData) + sizeof(foo.CharData);
显然,当使用联合的 CharData 成员时,代码尝试计算出结构中有趣的字节数。我的问题是,编译器警告联合未命名。所以我将其更改为
typedef struct STRUCT_FOO {
ULONG FooInfo;
union {
ULONG LongData;
USHORT ShortData;
UCHAR CharData;
} FooData;
} FOO;
但是当然我还需要更改最后一行。下面的结果总是会产生与原始结果完全相同的结果吗?
ULONG dataLength = offsetof(FOO, FooData) + sizeof(foo.FooData.CharData);
或者 CharData(或 ShortData 或 LongData)是否有可能不会在联合的开头对齐?
——编辑:谢谢您的回答。 这个问题的答案实际上为我提供了我需要的答案:指向联合的指针对象,经过适当转换,指向它的每个成员(或者如果一个成员是位域,则指向它所在的单元),反之亦然。。
无论如何,我应该选择这个问题的答案之一作为接受的答案吗?
I am modifying a bit of C code, that goes roughly like this:
typedef struct STRUCT_FOO {
ULONG FooInfo;
union {
ULONG LongData;
USHORT ShortData;
UCHAR CharData;
};
} FOO;
...
FOO foo;
ULONG dataLength = offsetof(FOO, CharData) + sizeof(foo.CharData);
Obviously, the code tries to figure out the number of interesting bytes in the struct, when using the CharData member of the union. My problem is, that the compiler warns about the union being unnamed. So I change it into
typedef struct STRUCT_FOO {
ULONG FooInfo;
union {
ULONG LongData;
USHORT ShortData;
UCHAR CharData;
} FooData;
} FOO;
But then of course I also need to change the last line. Will the following always yield exactly the same results as the original?
ULONG dataLength = offsetof(FOO, FooData) + sizeof(foo.FooData.CharData);
or is it possible, that CharData (or ShortData or LongData) will not be aligned at the beginning of the union?
-- edit: Thank you for your answers. The answer to this question actually provided me with the answer I needed: A pointer to a union object, suitably converted, points to each of its members (or if a member is a bitfield, then to the unit in which it resides), and vice versa..
Should I just choose one of the answers for this question as the accepted answer, anyway?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您调查过 __attribute__ 吗?
http://gcc.gnu.org/onlinedocs/ gcc-4.0.0/gcc/Type-Attributes.html
也许您可以通过使用它来确保您需要的内容是一致的?
Have you investigated
__attribute__
?http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Type-Attributes.html
Maybe you could make sure what you need is aligned by using this?
如果您符合以下条件,请参阅 Visual Studio 中的pragma pack (也)使用这个编译器。
See pragma pack in Visual Studio if you (also) use this compiler.