dp926460 2017-12-29 02:04
浏览 133
已采纳

如何使用结构体指针转换[] byte?

I'd like to use Go for low level project and avoid copying data.

I have a struct of fixed size:

type myStruct struct {
    a    uint8
    b    uint8
}

I would like to cast a pointer of my struct with this slice of bytes in order to read the value as if the slice of bytes was a struct without copying anything.

data := []byte{69,0}

var obj *myStruct

//something like:
obj = myStruct(data)
// or
obj = &myStruct(data)

In C it would be: obj = (struct myStruct*) data;

  • Is it possible ? What are the solutions to do so ? The best practice ?

I'd like to void using offset and index for the []byte.

Since a slice is not a fixed memory, I guess it'd be possible by converting []byte into a fixed array byte[0:2].

  • 写回答

1条回答 默认 最新

  • dongnaoben4456 2017-12-29 02:18
    关注

    You can cast unsafe.Pointer to *myStruct passing pointer to the first element of the bytes slice:

    import "unsafe"
    ...
    obj = (*myStruct)(unsafe.Pointer(&data[0]))
    

    test: https://play.golang.org/p/c7XO3dPKcLu

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

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题