dream752614590 2019-04-15 01:41
浏览 130
已采纳

golang:打包一个结构

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?

  • 写回答

1条回答 默认 最新

  • dsfds4551 2019-04-15 19:53
    关注

    So, per https://github.com/golang/go/wiki/cgo#struct-alignment-issues:

    Go doesn't support packed struct (e.g., structs where maximum alignment is 1 byte), you can't use packed C struct in Go. Even if your program passes compilation, it won't do what you want. To use it, you have to read/write the struct as byte array/slice.

    From "what" I understood, I've put together this: https://play.golang.org/p/OmdMVDMikSn.

    Essentially, set up the struct, and binary.Write it into a byte slice, the slice shows 10 bytes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题