更新时间:2023-09-26 19:30:10
存在 runtime.SetFinalizer
函数,但不能在C代码分配的任何对象上使用.
There exists the runtime.SetFinalizer
function, but it cannot be used on any object allocated by C code.
但是,您可以为每个需要自动释放的C对象创建一个Go对象:
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)
}