On Tue, Dec 3, 2019 at 7:20 PM Robert Johnstone <r.w.johnst...@gmail.com> wrote: > > The section on passing pointer to C in the cgo documentation is quite clear > that letting C hold pointer to Go memory is not allowed. I'd like to better > understand the limitation. Frankly, because of the architecture of a system > I'm working on, the inability to transport pointers is complicating matters. > > 1) The Go objects in question are certainly on the heap. > 2) The references in C are not needed to maintain the lifetime of the Go > objects. > > My understanding is that the main reason for the restriction is that Go might > move to a moving garbage collector. At the moment, unless there is definite > work on this, I'm inclined to break the rule and let the C code hold onto > pointers to Go memory. However, before committing to this approach, I'd like > to make sure I haven't missed any other reasons for the prohibition.
There is more background on this at https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md . The Go compiler compiles code to use a write barrier when storing pointers to memory. The C compiler obviously does not. When storing a Go pointer in C code, no write barrier is executed. This can cause the garbage collector to be confused about whether the pointer is reachable. In particular, it is absolutely critical that C code never store a Go pointer into Go memory. Still, while you have to be careful and I recommend against it, you may be able to get away with letting C code hold onto Go pointers across calls, in C memory. The Go values must be in the heap, not the stack. The Go values must be kept alive by existing Go pointers. But it's risky and I personally would never do it. Much better, if possible, to use a handle. Store the Go pointer in a map on the Go side, and pass the map key, an integer, to the C side. Then the C side can pass the integer back, and Go code look it up in the map to fetch the pointer. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcUCHrLtZrx1K418U_xVKCAxNM_A%2B%2B5-N4L7vUtN8FmO5w%40mail.gmail.com.