4

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
  • Can you post the code you want to translate so we have a rough idea of what your problem is? Commented Feb 16, 2015 at 22:02

1 Answer 1

10

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\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. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.