在cgo中的垃圾回收

huangapple go评论89阅读模式
英文:

Garbage collection in cgo

问题

我在Go中有以下使用cgo的代码:

func foo() {
    bar := new(C.struct_bar)
    ...
}

在函数执行完毕后,bar会被垃圾回收吗?还是我需要显式调用free函数来释放它?

英文:

I have the following code in Go which uses cgo:

  func foo() {
       bar := new(C.struct_bar)
       ...
  }

Will bar be garbage collected after the function finishes its execution or I need to explicitly call free?

答案1

得分: 5

是的,尽管struct_bar是一个C类型,但内存是由Go分配的,并且将由Go进行回收。

然而,由C分配的内存不会被Go的垃圾回收器(GC)跟踪。C代码应该自行管理这一点,但在像C.CString这样的情况下,由于Go触发了分配,你必须使用C.free手动释放内存。

英文:

Yes, even though the struct_bar is a C type, the memory is allocated by Go, and will be collected by Go.

Any memory allocated in C however is not tracked by the Go GC. The C code should manage this on it's own, but in cases like C.CString where Go triggers the allocation, you must manually free the memory with C.free.

huangapple
  • 本文由 发表于 2016年3月31日 21:06:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/36334384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定