Cgo: Write memory in C allocated by Go

212 Views Asked by At

For a non-struct slice in Go

a := []byte{0,1,2,3,4,5,6,7}

And pass to C via unsafe.Pointer()

C.some_method((*C.char)(unsafe.Pointer(&a[0])), C.int(len(a)))

Is it safe to write anything into this pointer with caution on it's length?

void some_method(char* a, int a_len) {
    for (int i=0; i<a_len; i++) {
        a[i] = i+1;
    }
}
1

There are 1 best solutions below

3
Wilson Luniz On

After a little research and reading comments, I think here're a few things to caution:

  • For async/multi-thread in C, you need to make sure GC won't collect you pointer. This can be done via runtime.KeepAlive()
  • GC may move you memory allocation. unsafe.Pointer won't get update if it do so(https://pkg.go.dev/unsafe#Pointer). But there's a pin mechanism coming soon(https://github.com/golang/go/issues/46787).
  • //go:uintptrescapes unlikely to work for CGO, use with caution.