简体   繁体   English

如何使用struct的指针强制转换[]字节?

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

I'd like to use Go for low level project and avoid copying data. 我想将Go用于低级项目并避免复制数据。

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. 我想用这slice of bytes pointer of my structpointer of my struct以便读取值,好像字节片是一个结构而不复制任何东西。

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; 在C中它将是: 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] . 由于切片不是固定存储器,我想通过将[]byte转换为固定数组byte[0:2]

You can cast unsafe.Pointer to *myStruct passing pointer to the first element of the bytes slice: 您可以将unsafe.Pointer*myStruct将指针传递给字节切片的第一个元素:

import "unsafe"
...
obj = (*myStruct)(unsafe.Pointer(&data[0]))

test: https://play.golang.org/p/c7XO3dPKcLu 测试: https//play.golang.org/p/c7XO3dPKcLu

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

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