如何将 Go 字符串数组转换为 C 字符串数组?
时间:2023-04-13
浏览:197
作者:佚名
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《如何将 Go 字符串数组转换为 C 字符串数组?》带大家来了解一下如何将 Go 字符串数组转换为 C 字符串数组?,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
我cgo在一个项目中使用,我想导出一个函数以供使用。这是我想要实现的示例:
package csplit
import (
"C"
"strings"
)
//export Split
/* The Split function takes two C strings, the second of which represents
a substring to split on, and returns an array of strings. Example:
Split("1,2", ",") // gives ["1", "2"]
*/
func Split(original *C.char, split *C.char) []*C.char {
goResult := strings.Split(C.GoString(original), C.GoString(split))
cResult := make([]*C.char, len(goResult))
for idx, substring := range goResult {
cResult[idx] = C.CString(substring)
}
return cResult
}
问题是返回类型是 Go 分配的数据,而不是移动到 C 堆中。这会引起恐慌:runtime error: cgo result has Go pointer
正确答案
您将返回一个 Go 切片,它是在 Go 中分配的,并且是与 C 数组不同的结构。您需要在 C 中分配一个数组:
//export Split
func Split(original *C.char, split *C.char) **C.char {
goResult := strings.Split(C.GoString(original), C.GoString(split))
cArray := C.malloc(C.size_t(len(goResult)) * C.size_t(unsafe.Sizeof(uintptr(0))))
// convert the C array to a Go Array so we can index it
a := (*[1<<30 - 1]*C.char)(cArray)
for idx, substring := range goResult {
a[idx] = C.CString(substring)
}
return (**C.char)(cArray)
}
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
热门专题
