问题
I have a use-case where C code will call Go function (exported by building Go as shared library). All this is in 64bit Linux.
The C code allocates a char*
buffer and passes it to the Go function. The Go code is expected to fill the buffer.
The receiving Go code is like:
//export FillBuf
func FillBuf(p uintptr, sz int) {
dest := toslice(p, sz)
// Copy into dest
}
The C code is like:
(Note: The type GoUintptr
is defined in auto-generated header by Go compiler)
char buf[100];
FillBuf((GoUintptr) &buf[0], 100);
I have the following Go code which "wraps" the C buffer into a Go slice:
func toslice(ptr uintptr, sz int) []byte {
h := reflect.SliceHeader{
Data: ptr,
Len: sz,
Cap: sz,
}
buf := *(*[]byte)(unsafe.Pointer(&h))
return buf
}
My understanding is that the Go will not GC the C buffer because it keeps track of the addresses it has allocated and C buffer is not among them.
Questions are:
- Is this safe? (I think it should be but not sure)
- Is this the only way? (The function signatures cannot be changed)
来源:https://stackoverflow.com/questions/61961793/wrapping-allocated-byte-buffer-in-c-as-go-slice-byte