Please consider this sample go code:
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
", sizeof(Packed_Struct) );
// printf("Sizeof UnPacked_Struct: %lu
", 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
", unsafe.Sizeof(GoStruct) )
fmt.Printf("meh type: %T
", meh)
}
The output is:
$ go run cgo.go
Hello world!
Sizeof Packed_Struct: 10
Sizeof UnPacked_Struct: 12
Sizeof GoStruct : 12
meh type: main._Ctype_void
Notice that the struct when packed takes 10 bytes, 12 otherwise. By default, my tries in Go seems to take 12 bytes as shown here.
Is there a Go-ish way to pack this struct so it uses only 10 bytes?