【问题标题】:Garbage collection and cgo垃圾收集和cgo
【发布时间】:2012-03-21 05:32:23
【问题描述】:

是否可以让 Go 中的垃圾收集器处理并释放通过 C 代码分配的内存?抱歉,我之前没有使用过 C 和 cgo,所以我的示例可能需要澄清一下。

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

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() 吗?

我在这里说得通吗?

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

【问题讨论】:

    标签: garbage-collection go cgo


    【解决方案1】:

    存在runtime.SetFinalizer函数,但不能用于C代码分配的任何对象。

    但是,您可以为每个需要自动释放的 C 对象创建一个 Go 对象:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多