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;
}
}
After a little research and reading comments, I think here're a few things to caution:
runtime.KeepAlive()unsafe.Pointerwon'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:uintptrescapesunlikely to work for CGO, use with caution.