Is it possible to make the garbage collector in Go handle and release memory allocated through C code? I apologize, I haven\'t used C and cgo before so my examples may need some
There exists the runtime.SetFinalizer function, but it cannot be used on any object allocated by C code.
However, you can create a Go object for each C object that needs to be freed automatically:
type Stuff struct {
cStuff *C.Stuff
}
func NewStuff() *Stuff {
s := &Stuff{C.NewStuff()}
runtime.SetFinalizer(s, (*Stuff).Free)
return s
}
func (s *Stuff) Free() {
C.Free(s.cStuff)
}