c - 在 Golang 中释放 C 变量?

标签 c go cgo

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

例如,如果我这样做:

    s := C.CString(`something`)

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

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

最佳答案

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))
}

关于c - 在 Golang 中释放 C 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26190410/

相关文章:

c - 访问从 void 指针转换的结构中的 char 指针

go lang,看不懂这段代码是做什么的

performance - Golang - "go run main.go"和编译之间的区别

go - 在mips64le下使用cgo构建静态库

windows - cgo - 如何将 go 字符串转换为 LPCWSTR

c - 难以访问嵌套的 C union 成员

c - 为什么用 argv[] 调用 sscanf() 只能使用一次?

c++ - 如何用C连续输出计算开始后的秒数?

c - 当应用程序崩溃或被操作系统杀死时内存中会发生什么

当它们应该是值时返回为 0 的 JSON 整数