英文:
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
函数分配的内存上才需要调用free
。C.CString
和C.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论