请考虑下面的示例代码:
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个字节,如下所示。
有没有一种可行的方法来压缩这个结构体,使它只使用10个字节?
1条答案
按热度按时间bq3bfh9z1#
因此,根据www.example.comhttps://github.com/golang/go/wiki/cgo#struct-alignment-issues:
根据我的理解,我总结了一下:https://play.golang.org/p/OmdMVDMikSn.
本质上,设置结构体,并将其
binary.Write
到字节切片中,切片显示10个字节。