在Golang中释放C变量?

Ala*_*air 3 c go cgo

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

例如,如果我这样做:

    s := C.CString(`something`)
Run Code Online (Sandbox Code Playgroud)

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

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

Von*_*onC 5

文件确实提到:

// 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
Run Code Online (Sandbox Code Playgroud)

维基显示了一个示例:

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))
}
Run Code Online (Sandbox Code Playgroud)

文章" C?Go?Cgo! "表明您不需要释放C数字类型:

func Random() int {
    var r C.long = C.random()
    return int(r)
}
Run Code Online (Sandbox Code Playgroud)

但你会为字符串:

import "C"
import "unsafe"

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