如何将Go字符串数组转换为C字符串数组? [英] How do I convert a Go array of strings to a C array of strings?

查看:154
本文介绍了如何将Go字符串数组转换为C字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用 cgo ,并且想要导出一个函数以供使用.这是我要实现的示例:

I am using cgo in a project, and I want to export a function for use. Here's an example of what I want to achieve:

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堆.出现以下错误:运行时错误:cgo结果具有Go指针

The problem is that the return type is Go allocated data, and not moved into the C heap. This panics with: runtime error: cgo result has Go pointer

推荐答案

您将返回Go切片,该切片在Go中分配,并且其结构与C数组不同.您需要在C中分配一个数组:

You're returning a Go slice which is allocated in Go, and is a different structure than a C array. You need to allocate an array in 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)
}

这篇关于如何将Go字符串数组转换为C字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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