用cgo制作C字符串 [英] Making a go string in C with cgo

查看:495
本文介绍了用cgo制作C字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从C中去掉一个字符串。我有指针和长度,所以如果我是这样做的话,我可以调用 C.GoStringN

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

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

//我有其他地方的s和n,我可以这样做吗?
const char * s = ...; //我拥有这个并且不想去释放它
int n = ...;

GoString st = {s,n};

我在这里将一个字符串从 char * 我的生命周期由我控制。 GoString 然后被用作go函数的参数:

  //输出Nbytes 
func Nbytes(s string)int {
...
}

会去垃圾收集器试图回收内存吗?

解决方案

Go的垃圾回收器不会尝试回收使用C内存分配器分配的内存。你所描述的应该是安全的。当然,你可能无法释放C内存,因为你不知道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 ?

解决方案

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.

这篇关于用cgo制作C字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆