在使用Cgo创建的结构体时,你需要手动释放它们吗?

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

Do I have to free structs created with Cgo?

问题

在Go代码中创建C结构体时,例如:

var data C.MyStruct_t

我需要在某个时候手动释放它们吗,就像我在使用CString时那样?对于CString,我经常会这样做:

ctitle := C.String(title)
defer C.free(unsafe.Pointer(&ctitle))
C.my_func(&ctitle)
英文:

I create C structs in my Go code, like this:

var data C.MyStruct_t

Do I have to free them manually at some point, like I do when I use CString? With CString I often do something like:

ctitle := C.String(title)
defer C.free(unsafe.Pointer(&ctitle))
C.my_func(&ctitle)

答案1

得分: 5

不。只有在通过C的*alloc函数分配的内存上才需要调用freeC.CStringC.CBytes函数在文档中已经说明会在内部进行释放,并要求使用C.free

在这种情况下,即使data的类型是C.MyStruct_t,它是在Go中分配的,因此将由Go的垃圾回收器处理。

英文:

No. You only call free on something that was allocated via the C *alloc functions. The C.CString and C.CBytes functions are documented as doing so internally, and requiring the use of C.free.

In this case even though data is of type C.MyStruct_t it is allocated in Go, and therefor will be handled by the Go garbage collector.

huangapple
  • 本文由 发表于 2017年1月24日 00:55:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/41811563.html
匿名

发表评论

匿名网友

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

确定