duankuaiwang2706 2015-02-16 13:56
浏览 88
已采纳

golang将内存转换为结构

I'm working on porting legacy code to golang, the code is high performance and I'm having trouble translating a part of the program that reads of a shared memory for later parsing. In c I would just cast the memory into a struct and access it normally. What is the most efficient and idiomatic to achieve the same result in go?

  • 写回答

1条回答 默认 最新

  • dqvs45976 2015-02-16 15:58
    关注

    If you want to cast an array of bytes to a struct, the unsafe package can do it for you. Here is a working example:

    There are limitations to the struct field types you can use in this way. Slices and strings are out, unless your C code yields exactly the right memory layout for the respective slice/string headers, which is unlikely. If it's just fixed size arrays and types like (u)int(8/16/32/64), the code below may be good enough. Otherwise you'll have to manually copy and assign each struct field by hand.

    package main
    
    import "fmt"
    import "unsafe"
    
    type T struct {
        A uint32
        B int16
    }
    
    var sizeOfT = unsafe.Sizeof(T{})
    
    func main() {
        t1 := T{123, -321}
        fmt.Printf("%#v
    ", t1)
    
        data := (*(*[1<<31 - 1]byte)(unsafe.Pointer(&t1)))[:sizeOfT]
        fmt.Printf("%#v
    ", data)
    
        t2 := (*(*T)(unsafe.Pointer(&data[0])))
        fmt.Printf("%#v
    ", t2)
    }
    

    Note that (*[1<<31 - 1]byte) does not actually allocate a byte array of this size. It's a trick used to ensure a slice of the correct size can be created through the ...[:sizeOfT] part. The size 1<<31 - 1 is the largest possible size any slice in Go can have. At least this used to be true in the past. I am unsure of this still applies. Either way, you'll have to use this approach to get a correctly sized slice of bytes.

    展开全部

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

报告相同问题?

悬赏问题

  • ¥15 没输出运行不了什么问题
  • ¥20 输入import torch显示Intel MKL FATAL ERROR,系统驱动1%,: Cannot load mkl_intel_thread.dll.
  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目
  • ¥30 海外项目,如何降低Google Map接口费用?
  • ¥15 fluentmeshing
  • ¥15 手机/平板的浏览器里如何实现类似荧光笔的效果
  • ¥15 盘古气象大模型调用(python)
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部