簡體   English   中英

使用cgo在C中創建一個go字符串

[英]Making a go string in C with cgo

我正在嘗試用C創建一個字符串。我有指針和長度,所以如果我從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用作go函數的參數:

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

將去的垃圾收集器試圖回收內存嗎?

Go的垃圾收集器不會嘗試回收使用C內存分配器分配的內存。 你所描述的應該是安全的。 當然,你可能無法釋放C內存,因為你不知道什么時候Go會用它來完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM