我们可以对结构布局做出假设吗?
用于在 C 上进行结构布局的算法是否有任何约定?
我希望能够在虚拟机中运行代码,以便能够具有与其 C 对应部分兼容的结构,就像 C# 互操作一样。为此,我需要知道对齐算法是如何工作的。我猜想一定有一个约定,因为它在 C# 上运行得很好。我想到了他们用来解决这个问题的可能算法,但我还没有找到任何证据证明它是正确的。
我认为它是这样工作的:
对于每个声明的字段(按声明的顺序)
- 查看该字段是否适合剩余字节(直到下一次对齐)
- 如果不适合,请对齐该字段;否则将其添加到当前偏移量,
例如,在 32 位系统上,对于如下结构:
{
byte b1;
byte b2;
int32 i1;
byte b3;
}
使用以下算法将如下所示:
{
byte b1;
byte b2;
byte[2] align1;
int32 i1;
byte b3;
byte[3] align2;
}
Is there any convention over the algorithm used to make the layouts of structs on C?
I want to be able to have a code running in a vm to be able to have structures compatible with their C counterparts, just like C# interop works. For this I will need to know how the alignment algorithm works. I gather there must be a convetion for that, as it works nicely on C#. I have in mind the probable algorithm they have used to work this out, but I haven't found any proof it is the right one.
Here's how I think it works:
for each declared field (by order of declaration)
- See if the field fits in the remaining bytes (until next alignment)
- If it doesn't fit, align this field; otherwise add it to current offset
for example, on a 32-bit system for a struct like:
{
byte b1;
byte b2;
int32 i1;
byte b3;
}
would be like this with this algorithm:
{
byte b1;
byte b2;
byte[2] align1;
int32 i1;
byte b3;
byte[3] align2;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,C 中的结构对齐取决于所使用的编译器,尤其是处理结构声明时有效的编译器选项。您不能做出任何一般性假设,只能说对于使用特定设置编译的特定程序中的特定结构,可以确定结构布局。
也就是说,您的猜测与大多数编译器可能对默认对齐设置的操作非常匹配。
In general, structure alignment in C depends on the compiler used, and especially the compiler options in effect at the time the structure declaration is processed. You can't make any general assumptions except to say that for a particular structure in a particular program compiled with particular settings, the structure layout can be determined.
That said, your guess closely matches what most compilers are likely to do with default alignment settings.