Making a go string in C with cgo

huangapple go评论86阅读模式
英文:

Making a go string in C with cgo

问题

我正在尝试从C语言创建一个Go字符串。我有指针和长度,所以如果我从Go语言中进行操作,我可以调用C.GoStringN函数。

cgo生成了GoString结构体,所以我想知道是否可以直接使用它:

// 由cgo生成的结构体
typedef struct { const char *p; GoInt n; } GoString;

// 我从其他地方得到了s和n,我可以这样做吗?
const char* s = ... ; // 我拥有这个指针,不希望Go语言释放它
int n = ... ;

GoString st = {s, n};

我在这里使用它将一个我控制生命周期的char*转换为Go字符串。然后,将GoString作为参数传递给一个Go函数:

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

Go语言的垃圾回收器会尝试回收这块内存吗?

英文:

I'm trying to make a go string from C. I have the pointer and the length, so if I was doing it from go, I could call the C.GoStringN function.

cgo generates the GoString struct, so I was wondering if I could use it directly:

// 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 } ;

I'm using this in here to make a go string out of a char* whose lifetime I control. The GoString is then used as an argument to a go function:

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

Will go's garbage collector attempt to reclaim the memory ?

答案1

得分: 3

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

英文:

Go's garbage collector will not try to reclaim memory allocated using the C memory allocator. What you are describing should be safe. Of course, you may not be able to free the C memory, because you don't know when Go will be done with it.

huangapple
  • 本文由 发表于 2017年6月11日 01:05:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/44475923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定