从不安全中获取特定字节片段的最佳(最安全+性能最佳)方法是什么

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?

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.