Garbage collection and cgo

后端 未结 1 716
小鲜肉
小鲜肉 2021-02-04 11:15

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

1条回答
  •  死守一世寂寞
    2021-02-04 11:54

    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)
    }
    

    0 讨论(0)
提交回复
热议问题