Type data structure {
Size, MsgType uint 16
Sequence uint32
// ...
}
Golang compiler can work normally with or without padding. The runtime knows the layout of the data, unlike C, which directly casts it, so it needs to know how to align it.
You can know the alignment length of each field with unsafe. Alignof, but this is not necessary.
Main packaging
/*
# include & ltstdint.h & gt
# Miscellaneous note package (push, 1)
Typedef structure {
Uint 16_t size;
uint 16 _ t msg type;
Uint32_t sequence;
uint 8 _ t data 1;
uint32 _ t data2
uint 16 _ t data 3;
} mydata
# Miscellaneous note package (pop)
mydata foo = {
1, 2, 3, 4, 5, 6,
};
int size() {
Returns sizeof (mydata);
}
*/
Import "c"
Import (
"Bytes"
"Coded/Binary"
" fmt "
"Journal"
"unsafe"
)
func main() {
Bs := C.GoBytes (unsafe. Pointer (& ampC.foo), C.size ())
fmt。 Printf("len %d data %v\n ",len(bs),bs)
Variable data structure {
Size, Msytype uint 16
Sequence uint32
Data 1 uint8
Data 2 uint32
Data 3 uint 16
}
Error: = binary. Read (bytes. NewReader(bs), binary. little endian & amp; Data)
If err! = zero {
Journal. Fatal (error)
}
fmt。 Printf("%v\n ",data) // { 1 2 3 4 5 6}
Buf := new (bytes. Buffer)
Binary. Write (buf, binary. BigEndian, data)
fmt。 Printf("%d %v\n ",buf。 Len(),buf。 bytes())// 15[0 1 0 2 0 0 0 3 4 0 0 0 5 0 6]
}