Layout for struct prefix

狂风中的少年 提交于 2020-01-14 15:00:14

问题


The C/C++ languages don't reorder struct members in memory and never insert padding before the first member. But if I have 2 structures that start with the same members, can I cast between them if I only access the common members? In other words, is struct layout greedy? My concrete case is casting between VIDEOINFOHEADER and VIDEOINFOHEADER2


回答1:


The C++ standard contains the following statement which, however, only applies to unions (9.2 [class.member] paragraph 19):

If a standard-layout union contains two or more standard-layout structs that share a common initial sequence, and if the standard-layout union object currently contains one of these standard-layout structs, it is permitted to inspect the common initial part of any of them. Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

I didn't see any other guarantee with respect to partially defined structures in either the C or the C++ standard. That doesn't mean it isn't there, though, just that I haven't found it with a quick scan of a couple of relevant sections.




回答2:


Short answer: yes. Mostly.

Compilers cannot re-order struct members: true. I'm not so sure about the padding, IFAIR structure member alignment is implementation defined.

But, a compiler is consistent when laying out structures. It has to be, or you'd never be able to write and then read back structures to files. And most compilers use 'sane' rules for structure layout, so you can write from one program and read in with another, even if they are different compilers on different systems.

Most of the time. There are no exactly defined rules for structure layout. So occasionally you get bitten by relying on the "natural" layout to match, when it doesn't. But in this case, you should be safe.




回答3:


I believe that it is not guaranteed to work in theory, but it most probably would always work. Apart from there being no padding before the first members of structs (in C), there is no guarantee on what padding exists between the members, so theoretically the two structs could have different layouts. In practice though, you would expect the padding to be the same for both for most padding rules that you can think of.

What you could do (not in your specific example, though) is start both structs with a single member which is another struct, and cast to a pointer to the first member.



来源:https://stackoverflow.com/questions/20788934/layout-for-struct-prefix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!