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?

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.