dongyi2006
2014-10-04 06:45
浏览 281
已采纳

在Golang中释放C变量?

I'm confused about which variables need to be freed if I'm using C variables in Go.

For example, if I do this:

    s := C.CString(`something`)

Is that memory now allocated until I call C.free(unsafe.Pointer(s)), or is that OK to be garbage collected by Go when the function ends?

Or is it only variables that are created from the imported C code that need to be freed, and these C variables created from the Go code will be garbage collected?

图片转代码服务由CSDN问答提供 功能建议

如果我在Go中使用C变量,我很困惑哪些变量需要释放。

例如,如果我这样做:

  s:= C.CString(`something`)
   
 
 

在我调用 C.free(unsafe.Pointer(s))之前,是否一直在分配该内存,还是可以在函数结束时由Go进行垃圾回收?

还是仅需要从导入的C代码创建的变量需要被释放,而这些从Go代码创建的C变量将被垃圾回收?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshao4207 2014-10-04 06:47
    已采纳

    The documentation does mention:

    // Go string to C string
    // The C string is allocated in the C heap using malloc.
    // It is the caller's responsibility to arrange for it to be
    // freed, such as by calling C.free (be sure to include stdlib.h
    // if C.free is needed).
    func C.CString(string) *C.char
    

    The wiki shows an example:

    package cgoexample
    
    /*
    #include <stdio.h>
    #include <stdlib.h>
    
    void myprint(char* s) {
            printf("%s", s);
    }
    */
    import "C"
    
    import "unsafe"
    
    func Example() {
            cs := C.CString("Hello from stdio
    ")
            C.myprint(cs)
            C.free(unsafe.Pointer(cs))
    }
    

    The article "C? Go? Cgo!" shows that you don't need to free C numeric types:

    func Random() int {
        var r C.long = C.random()
        return int(r)
    }
    

    But you would for string:

    import "C"
    import "unsafe"
    
    func Print(s string) {
        cs := C.CString(s)
        C.fputs(cs, (*C.FILE)(C.stdout))
        C.free(unsafe.Pointer(cs))
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题