英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论