Thanks for your response!

How does it keep alive for at least the duration of the cgo call? After the 
pointer is copied and passed to the cgo call, it will become unreachable. 
After it is swept by GC, pointers point to that part of memory will no 
longer exist on the Go-managed heap.

Do you mean that sweep phrase cannot be started before the end of that cgo 
call?

在 2019年3月22日星期五 UTC+8上午2:37:36,Ian Lance Taylor写道:
>
> On Wed, Mar 20, 2019 at 10:56 PM Cholerae Hu <chole...@gmail.com 
> <javascript:>> wrote: 
> > 
> > package main 
> > 
> > // void a(long *p) {} 
> > import "C" 
> > 
> > import ( 
> > "unsafe" 
> > ) 
> > 
> > //go:noinline 
> > func b() { 
> > x := int64(0) 
> > C.a((*C.long)(unsafe.Pointer(&x))) 
> > // do something without x 
> > } 
> > 
> > func main() { 
> > b() 
> > } 
> > 
> > x should be considered unreachable after C.a . If x is something 
> allocated on heap, do I need to use runtime.KeepAlive(x) to make sure x 
> will not be garbage collected? 
>
> It's not necessary to use runtime.KeepAlive to keep pointers passed to 
> cgo functions alive.  They will be live for at least the duration of 
> the cgo call. 
>
> 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.
For more options, visit https://groups.google.com/d/optout.

Reply via email to