垃圾收集和CGO [英] Garbage collection and cgo

查看:62
本文介绍了垃圾收集和CGO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Go句柄中创建垃圾收集器并释放通过C代码分配的内存?抱歉,我之前没有使用过C和cgo,所以我的示例可能需要澄清.

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.

让我们说您有一些想使用的C库,并且该库分配了一些需要手动释放的内存.我想做的是这样的:

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
}

在Go运行时中没有对* Stuff的引用时,垃圾收集器是否可以调用Stuff.Free()?

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

我在这里有意义吗?

也许更直接的问题是:是否有可能通过编写一个在该对象的引用为零时运行时调用的函数来使运行时自动处理C分配的内存的清理?

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?

推荐答案

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

这篇关于垃圾收集和CGO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆