我正在尝试从 C 生成一个 go 字符串。我有指针和长度,所以如果我从 go 开始,我可以调用 C.GoStringN
函数。
cgo
生成了 GoString
结构,所以我想知道我是否可以直接使用它:
// struct generated by cgo
typedef struct { const char *p; GoInt n; } GoString;
// I have s and n from somewhere else, can I do this ?
const char* s = ... ; // I own this and dont want go to free it
int n = ... ;
GoString st = {s, n } ;
我在 here 中使用它从生命周期由我控制的 char*
生成一个 go string。 GoString
然后用作 go 函数的参数:
//export Nbytes
func Nbytes(s string) int {
...
}
Go 的垃圾收集器会尝试回收内存吗?
最佳答案
Go 的垃圾收集器不会尝试回收使用 C 内存分配器分配的内存。你所描述的应该是安全的。当然,你可能无法释放 C 内存,因为你不知道 Go 何时会用完它。
关于go - 用 cgo 在 C 中制作一个 go 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44475923/