duanci6484
2017-11-17 16:01
浏览 531
已采纳

从Go访问const char *类型的C数组

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"}

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

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?

图片转代码服务由CSDN问答提供 功能建议

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

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

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

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

...结果 就是这样:

NAME_OF_FIRST_THING

FIRST_THING < p> ING

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

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanjiwei1283 2017-11-17 16:31
    已采纳

    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
    

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题