go - 用 cgo 在 C 中制作一个 go 字符串

标签 go cgo

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

我在 here 中使用它从生命周期由我控制的 char* 生成一个 go string。 GoString 然后用作 go 函数的参数:

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

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

最佳答案

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

关于go - 用 cgo 在 C 中制作一个 go 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44475923/

相关文章:

c - 如何将 uint8_t 数组从 C 发送到 GO

c - 如何从 Go 代码调用 Java Native Interface C 函数?

macos - 为较旧的 Mac OS 版本构建 golang 应用程序的正确方法是什么?

go - 将 strfmon 与 cgo 一起使用

c++ - 连接 C++ 和 Go

Golang 将 UTF16 字符串转换为 UTF8

compilation - Windows 64 位的 .go 文件编译错误

jquery - 如果有新请求进来,如何取消进行中的请求?

postgresql - 如何将 Docker Web 应用程序容器连接到 Docker PostgreSQL 容器?

go - 为什么我的 golang 程序创建了这么多线程?