在Golang中释放C变量?

时间:2014-10-04 06:45:07

标签: c go cgo

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

例如,如果我这样做:

    s := C.CString(`something`)

现在是否已分配内存,直到我调用C.free(unsafe.Pointer(s)),或者当函数结束时Go是否可以进行垃圾回收?

或者只是从导入的C代码创建的变量需要被释放,并且从Go代码创建的这些C变量将被垃圾收集?

1 个答案:

答案 0 :(得分:5)

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

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\n")
        C.myprint(cs)
        C.free(unsafe.Pointer(cs))
}

文章“C? Go? Cgo!”表示您不需要释放C数字类型:

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

但是你想要字符串:

import "C"
import "unsafe"

func Print(s string) {
    cs := C.CString(s)
    C.fputs(cs, (*C.FILE)(C.stdout))
    C.free(unsafe.Pointer(cs))
}