简体   繁体   English

golang将内存转换为struct

[英]golang cast memory to struct

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. 我正在努力将遗留代码移植到golang,代码是高性能的,我在翻译读取共享内存的程序的一部分时遇到了麻烦,以便以后解析。 In c I would just cast the memory into a struct and access it normally. 在c中我只是将内存转换为结构并正常访问它。 What is the most efficient and idiomatic to achieve the same result in go? go中获得相同结果的最有效和最惯用的是什么?

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. 以这种方式可以使用的struct字段类型存在限制。 Slices and strings are out, unless your C code yields exactly the right memory layout for the respective slice/string headers, which is unlikely. 切片和字符串都没有,除非你的C代码为各个切片/字符串头准确地产生了正确的内存布局,这是不可能的。 If it's just fixed size arrays and types like (u)int(8/16/32/64), the code below may be good enough. 如果它只是固定大小的数组和类型(如(u)int(8/16/32/64)),下面的代码可能就足够了。 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\n", t1)

    data := (*(*[1<<31 - 1]byte)(unsafe.Pointer(&t1)))[:sizeOfT]
    fmt.Printf("%#v\n", data)

    t2 := (*(*T)(unsafe.Pointer(&data[0])))
    fmt.Printf("%#v\n", t2)
}

Note that (*[1<<31 - 1]byte) does not actually allocate a byte array of this size. 请注意, (*[1<<31 - 1]byte)实际上并不分配此大小的字节数组。 It's a trick used to ensure a slice of the correct size can be created through the ...[:sizeOfT] part. 这是一个技巧,用于确保通过...[:sizeOfT]部分创建正确大小的切片。 The size 1<<31 - 1 is the largest possible size any slice in Go can have. 大小1<<31 - 1是Go中任何切片可能具有的最大可能大小。 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. 无论哪种方式,您都必须使用此方法来获取正确大小的字节片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM