用 cgo 在 C 中制作一个 go 字符串

Making a go string in C with cgo

我正在尝试从 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 字符串。 GoString 然后用作 go 函数的参数:

//export Nbytes
func Nbytes(s string) int {
  ...
}

go 的垃圾收集器会尝试回收内存吗?

Go 的垃圾收集器不会尝试回收使用 C 内存分配器分配的内存。你所描述的应该是安全的。当然,你可能无法释放 C 内存,因为你不知道 Go 什么时候会用完它。