如果我在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释放内存是否有效?
package cgoexample
/*
#include <stdio.h>
#include <stdlib.h>
void myprint(char* s) {
printf("%s", s);
if (s != NULL) {
free(s);
}
}
*/
import "C"
import "unsafe"
func Example() {
cs := C.CString("Hello from stdio\n")
C.myprint(cs)
}