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

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿