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条回答 默认 最新
- dqvs45976 2015-02-16 23:58关注
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 size1<<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.本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥100 set_link_state
- ¥15 虚幻5 UE美术毛发渲染
- ¥15 CVRP 图论 物流运输优化
- ¥15 Tableau online 嵌入ppt失败
- ¥100 支付宝网页转账系统不识别账号
- ¥15 基于单片机的靶位控制系统
- ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度