请考虑此示例代码:
package main
//#include <stdio.h>
//#include <stdint.h>
//#pragma pack(push, 1)
//struct Packed_Struct {
// uint16_t A;
// uint16_t B;
// uint32_t C;
// uint16_t D;
//};
//#pragma pack(pop)
//
//struct UnPacked_Struct {
// uint16_t A;
// uint16_t B;
// uint32_t C;
// uint16_t D;
//};
//
//
//void print_C_struct_size(){
// struct Packed_Struct Packed_Struct;
// struct UnPacked_Struct UnPacked_Struct;
// printf("Sizeof Packed_Struct: %lu\n", sizeof(Packed_Struct) );
// printf("Sizeof UnPacked_Struct: %lu\n", sizeof(UnPacked_Struct) );
// return;
//}
//
import "C"
import(
"fmt"
"unsafe"
)
type GoStruct struct{
A uint16
B uint16
C uint32
D uint16
}
func main(){
fmt.Println("Hello world!")
meh := C.print_C_struct_size()
var GoStruct GoStruct
fmt.Printf("Sizeof GoStruct : %d\n", unsafe.Sizeof(GoStruct) )
fmt.Printf("meh type: %T\n", meh)
}
输出是:
$ go run cgo.go
Hello world!
Sizeof Packed_Struct: 10
Sizeof UnPacked_Struct: 12
Sizeof GoStruct : 12
meh type: main._Ctype_void
请注意,打包时的结构需要10个字节,否则为12个字节。默认情况下,我在Go中的尝试似乎需要12个字节,如此处所示。
是否有一种Go-ish方法来打包这个结构,所以它只使用10个字节?
所以,根据https://github.com/golang/go/wiki/cgo#struct-alignment-issues:
Go不支持压缩结构(例如,最大对齐为1字节的结构),您不能在Go中使用压缩的C结构。即使你的程序通过编译,它也不会做你想要的。要使用它,您必须将结构读/写为字节数组/切片。
从我理解的“什么”,我把这个拼凑起来:https://play.golang.org/p/OmdMVDMikSn。
本质上,设置结构,并将binary.Write
设置为字节切片,切片显示10个字节。