douyi9705 2012-03-02 17:47
浏览 47
已采纳

垃圾收集和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.

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?

  • 写回答

1条回答 默认 最新

  • dqhdz04240 2012-03-02 18:27
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用