Wrapping allocated byte buffer in C as Go slice ([]byte) [duplicate]

℡╲_俬逩灬. 提交于 2021-01-29 05:04:06

问题


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:

  1. Is this safe? (I think it should be but not sure)
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!