如题所述
ç¨golang解æäºè¿å¶åè®®æ¶ï¼å
¶å®æ²¡å¿
è¦ç®¡ç»æä½çå段ç对é½è§åï¼ä½åµè¯è¨è§èä¹æ²¡æè§å®å¦ä½å¯¹é½ï¼ä¹å°±æ¯æ²¡æè§åãç¨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]
}
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]
}
温馨提示:答案为网友推荐,仅供参考