从Go访问const char *类型的C数组 [英] Access C array of type const char * from Go

查看:147
本文介绍了从Go访问const char *类型的C数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C类型的文件,数组的类型为const char *,我们称它为myStringArray[],类似:

I have a C file with an array of type const char *, lets call it myStringArray[], something like:

const char *myStringArray[] = {
  "NAME_OF_FIRST_THING",
  "NAME_OF_SECOND_THING",
  "NAME_OF_THIRD_THING"}

我需要使用cgo转到该C数组的索引,并将数组项转换为Go字符串.以下代码可以编译,但不能正常运行;您可以从下面的输出中看到,它是沿着字符串而不是数组进行索引:

I need Go to index into that C array, using cgo, and convert an array entry into a Go string. The following code compiles but does not work correctly; you can see from the output that follows, it is indexing along the strings rather than up the array:

myGoString := C.GoString((*C.char) (unsafe.Pointer(uintptr(unsafe.Pointer(C.myStringArray)) + uintptr(index) * unsafe.Sizeof(C.myStringArray))))

...结果是这样的:

...result being this:

NAME_OF_FIRST_THING

FIRST_THING

ING

仅供参考,其目的是在服务器上解码在运行C的嵌入式平台上创建的日志文件,因此需要重新使用相同的日志记录索引文件.

FYI, the purpose of this is to decode on a server a log file that was created on an embedded platform running C, hence the need to re-use the same logging index files.

我已经随机刺了几个小时,但没有成功.谁能纠正我的结构,或提供替代方法?

I've been stabbing at this randomly for a few hours now without success. Can anyone correct my construction, or provide an alternative?

推荐答案

虽然您可以自己进行指针算术,但先将C数组转换为Go slice更加安全便捷.

While you could do the pointer arithmetic yourself, it's safer and more convenient to convert the C array into a Go slice first.

arraySize := 3
cStrings := (*[1 << 30]*C.char)(unsafe.Pointer(&C.myStringArray))[:arraySize:arraySize]

for _, cString := range cStrings {
    fmt.Println(C.GoString(cString))
}

// prints:
// NAME_OF_FIRST_THING
// NAME_OF_SECOND_THING
// NAME_OF_THIRD_THING

相关cgo Wiki条目: https: //github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices

Relevant cgo wiki entry: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices

这篇关于从Go访问const char *类型的C数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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