我应该相信 “aligncheck” 报告的大小吗?

huangapple go评论98阅读模式
英文:

Should I trust the size reported by "aligncheck"

问题

我有一个如下所示的结构体:

type MyStruct struct {
    A [10]byte
    B uint64
    C uint16
}

并且使用以下方式与binary.Read一起使用:

err = binary.Read(r, binary.BigEndian, &mystruct)  // mystruct 是 MyStruct 类型

我得到了mystruct中所有字段的正确值。并且从读取器r中读取的一些后续代码也得到了正确的结果。

但是,aligncheck方面的MyStruct的大小可能是24,但当前为32。但对于二进制字节读取,它应该占用20个字节。

所以我不确定我只是幸运地得到了正确的结果,还是Go工具链的某个部分会将结构体打包到适当的大小?

英文:

I have a struct defined as below:

type MyStruct struct {
    A [10]byte
    B uint64
    C uint16
}

And use with binary.Read as below

err = binary.Read(r, binary.BigEndian, &mystruct)  // mystruct is Mystruct type

I got the correct value for all fields in mystruct. And some following code read from Reader r all get correct result.

But the aligncheck side MyStruct could have size 24 but currently is 32. But for the binary byte read, it should take 20 bytes.

So I am not sure I just got luck to get the correct result or some part of the go tool chain would pack the struct to proper size?

答案1

得分: 3

正如Tim Cooper在他的评论中所说,您正在比较同一数据的两种不同表示方式。aligncheck告诉您一个结构体实例在内存(堆/栈)中占用了多少空间,这受到结构体字段对齐和填充的影响,原因在其他地方有详细解释

另一方面,binary.Read.Write并不试图以边界对齐的方式将对象存储在内存中;它们只是写入一串连续的字节流。因此,无论字段的顺序如何,它们都会输出相同大小的结构体,并且始终是结构体的最小大小(因为没有添加填充)。

英文:

As Tim Cooper stated in his comment, you're comparing two different representations of the same data. aligncheck tells you how much space is occupied in memory (heap/stack) by an instance of a struct, which is affected by struct field alignment and padding, for reasons explained at length elsewhere.

binary.Read and .Write, on the other hand, are not trying to store objects in memory with boundary alignment; they're just writing a stream of contiguous bytes. Therefor these will output the same size struct regardless of the order of fields, and it will always be the minimum size of the struct (because there is no padding added).

答案2

得分: 1

在重新查看二进制源代码后,它获取了结构体中每个字段的实际长度,然后从r读取器中读取正确数量的数据,并将值分别赋给每个字段。因此,结构体在内存中的对齐方式并不重要。

英文:

After revisited the binary's source code, it gets the real length of each field of the struct and then read the correct amount of data from r reader and assign the value to each field respectively. So it doesn't matter how the struct is aligned in the memory.

huangapple
  • 本文由 发表于 2017年8月18日 19:02:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/45755110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定