简体   繁体   中英

How to cast a []byte with a pointer of struct?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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