从`unsafe.Pointer`获取特定字节片段的最佳(最安全+最高性能)方法是什么?

huangapple go评论77阅读模式
英文:

What is the best (safest + most performant) way of getting a specific slice of bytes from an unsafe.Pointer

问题

我正在尝试将这段C++代码转换为Go语言。

这是C代码的简要说明:

static const char *pSharedMem = NULL;
int sessionInfoOffset;

return pSharedMem + pHeader->sessionInfoOffset;

这是我(伪代码)的Go代码:

var pSharedMem unsafe.Pointer
sessionInfoLen C.int

byteSlice := C.GoBytes(pSharedMem, pHeader.sessionInfoLen)
return byteSlice[pHeader.sessionInfoOffset:]

我从来没有真正编写过C代码,也不知道从unsafe.Pointer中检索字节切片的这种方式是否正确。这种方法是否会出错(复制错误的内存片段或其他问题),以及这种方法的性能如何?我是否在做一些非常愚蠢的事情?

英文:

I'm trying to convert this c++ to go.

This is in short what the c code is doing:

static const char *pSharedMem = NULL;
int sessionInfoOffset;

return pSharedMem + pHeader->sessionInfoOffset;

This is my (pseudo) go code:

var pSharedMem unsafe.Pointer
sessionInfoLen C.int

byteSlice := C.GoBytes(pSharedMem, pHeader.sessionInfoLen)
return byteSlice[pHeader.sessionInfoOffset:]

I've never really written any C code and I have no idea if this a good way of retrieving a byte slice from an unsafe.Pointer. Could go anything wrong with this (copying wrong piece of memory or something) and is this performant of am I doing something really stupid?

答案1

得分: 1

GoBytes 是最安全的方法。你仍然需要确保数组在整个复制操作期间存在,但一旦你复制了字节,就知道它不能从 cgo 中更改。只要被复制的内存不太大,或者复制会导致性能问题,这就是最好的方法。

如果你想通过切片直接访问字节,可以像这样将其切片为数组:

size := pHeader.sessionInfoLen
byteSlice := (*[1<<30]byte)(pSharedMem)[:size:size]

这样可以避免复制,但你需要管理来自 cgo 的并发访问,并确保在从 Go 访问时不释放内存。

英文:

GoBytes is going to be the safest method. You still have to ensure that the array exists for the entirety of the copy operation, but once you have the bytes copied, you know it can't be changed from cgo. As long as the memory being copied isn't too large, or the copy presents a performance problem, this is the way to go.

If you want direct access to the bytes via a slice, you can slice it as an array like so:

size := pHeader.sessionInfoLen
byteSlice := (*[1&lt;&lt;30]byte)(pSharedMem)[:size:size]

This saves you the copy, but you then have to manage concurrent access from cgo, and ensure the memory isn't released while you're accessing it from Go.

huangapple
  • 本文由 发表于 2015年3月22日 06:21:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/29188730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定