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

在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?

  • 写回答

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

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题