问题描述
我试图从C中去掉一个字符串。我有指针和长度,所以如果我是这样做的话,我可以调用 我在将一个字符串从 会去垃圾收集器试图回收内存吗? 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 I'm using this in here to make a go string out of a 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字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! C.GoStringN $ c $功能。
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 {
...
}
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 } ;
char*
whose lifetime I control. The GoString
is then used as an argument to a go function: //export Nbytes
func Nbytes(s string) int {
...
}