小编典典

用cgo在C语言中编写go字符串

go

我正在尝试从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 } ;

我在这里用它来char*控制我的生命。在GoString随后作为参数传递给函数去:

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

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


阅读 293

收藏
2020-07-02

共1个答案

小编典典

Go的垃圾回收器不会尝试回收使用C内存分配器分配的内存。您所描述的应该是安全的。当然,您可能无法释放C内存,因为您不知道Go将在何时完成。

2020-07-02