如何通过golang中的CGO将Go字符串复制到C char *中? [英] How do I copy a Go string to a C char * via CGO in golang?

查看:1264
本文介绍了如何通过golang中的CGO将Go字符串复制到C char *中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过CGO将Go字符串复制到char *中。

I want to copy a Go string into a char * via CGO.

我是否允许这样做?

Am I allowed to do this something like this?

func copy_string(cstr *C.char) {

    str := "foo"
    C.GoString(cstr) = str

}


推荐答案

根据 cgo文档,您需要使用C.CString函数将Go字符串转换为C字符串:

According to the cgo documentation you need to use the C.CString function to convert a Go string to a C string:

cstr = C.CString(str)

请注意,C.CString函数会为您分配内存,但不会释放内存,因此您可以通过以下调用释放内存:

Be aware that C.CString function allocates the memory for you, but won't release it, so it is your responsability to freed the memory with a call like:

C.free(unsafe.Pointer(cstr))

这篇关于如何通过golang中的CGO将Go字符串复制到C char *中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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