Pregunta

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 clarification.

Lets say you've got some C library that you'd like to use and this library allocates some memory that needs to be freed manually. What I'd like to do is something like this:

package stuff

/*
#include <stuff.h>
*/
import "C"

type Stuff C.Stuff

func NewStuff() *Stuff {
    stuff := Stuff(C.NewStuff()) // Allocate memory

    // define the release function for the runtime to call
    // when this object has no references to it (to release memory)   
    // In this case it's stuff.Free()     

    return stuff

}

func (s Stuff) Free() {
    C.Free(C.Stuff(s)) // Release memory
}

Is there any way for the garbage collector to call Stuff.Free() when there are no references to *Stuff in the Go runtime?

Am I making sense here?

Perhaps a more direct question is: Is it possible to make the runtime automatically handle the cleanup of C allocated memory by writing a function that the runtime calls when there are zero references to that object?

¿Fue útil?

Solución

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)
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top