如果我在 Go 中使用 C 变量,我对哪些变量需要释放感到困惑。
例如,如果我这样做:
s := C.CString(`something`)
在我调用 C.free(unsafe.Pointer(s))
之前,该内存现在是否已分配,或者当函数结束时是否可以由 Go 进行垃圾回收?
还是只有从导入的 C 代码创建的变量需要释放,而这些从 Go 代码创建的 C 变量将被垃圾收集?
最佳答案
// 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
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/