3

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

例如,如果我这样做:

    s := C.CString(`something`)

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

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

4

1 回答 1

6

文档确实提到

// 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显示了一个示例

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))
}
于 2014-10-04T06:47:34.480 回答