1 回答

TA貢獻1966條經驗 獲得超4個贊
用golang解析二進制協(xié)議時,其實沒必要管結構體的字段的對齊規(guī)則,何況語言規(guī)范也沒有規(guī)定如何對齊,也就是沒有規(guī)則。用encoding/binary.Read函數直接讀入struct里就行,struct就像c那樣寫
type Data struct {
Size, MsgType uint16
Sequence uint32
// ...
}
golang編譯器加不加padding,Read都能正常工作,runtime知道Data的布局的,不像C直接做cast所以要知道怎樣對齊。
用unsafe.Alignof可以知道每個field的對齊長度,但沒必要用到。
package main
/*
#include <stdint.h>
#pragma pack(push, 1)
typedef struct {
uint16_t size;
uint16_t msgtype;
uint32_t sequnce;
uint8_t data1;
uint32_t data2;
uint16_t data3;
} mydata;
#pragma pack(pop)
mydata foo = {
1, 2, 3, 4, 5, 6,
};
int size() {
return sizeof(mydata);
}
*/
import "C"
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"unsafe"
)
func main() {
bs := C.GoBytes(unsafe.Pointer(&C.foo), C.size())
fmt.Printf("len %d data %v\n", len(bs), bs)
var data struct {
Size, Msytype uint16
Sequence uint32
Data1 uint8
Data2 uint32
Data3 uint16
}
err := binary.Read(bytes.NewReader(bs), binary.LittleEndian, &data)
if err != nil {
log.Fatal(err)
}
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]
}
- 1 回答
- 0 關注
- 864 瀏覽
添加回答
舉報