英文:
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<<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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论