为了账号安全,请及时绑定邮箱和手机立即绑定

golang怎么返回结构体?

golang怎么返回结构体?

Go
有只小跳蛙 2018-12-14 15:11:38
golang怎么返回结构体
查看完整描述

1 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

用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]
}


查看完整回答
反对 回复 2019-01-06
  • 1 回答
  • 0 关注
  • 784 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信