droxy80248 2018-11-07 07:42
浏览 185
已采纳

直接C指针转换

I have this C code:

uint8_t *data[BUF_SIZE];
data = ...;

// extern void goReadData(uint8_t *data, int bufferSize);
goReadData(data, BUF_SIZE)

And in the GO Code I'm trying to use the data pointer as a GO array or slice, I want to retrieve an []uint8 from the *C.uint8_t. I know the size of the data

//export goReadData
func goReadData(data *C.uint8_t, bufferSize C.int) {

    fmt.Printf("Data type %v
", reflect.TypeOf(data))
    // print 1: Data type *main._Ctype_uchar


    // Solution 1: GoBytes
    // works but really slow (memory copy I think)
    goBytes := C.GoBytes(unsafe.Pointer(data), bufferSize)
    fmt.Printf("goBytes type %v
", reflect.TypeOf(goBytes))
    // print 2: goBytes type []uint8


    // Solution 2: direct pointer
    // Really fast, but wrong type at the end
    // unsafe.Pointer to the C array
    unsafePtr := unsafe.Pointer(data)

    // convert unsafePtr to a pointer of the type *[1 << 30]C.uint8_t
    arrayPtr := (*[1 << 30]C.uint8_t)(unsafePtr)

    // slice the array into a Go slice, with the same backing array
    // as data, making sure to specify the capacity as well as
    // the length.
    length := int(bufferSize)
    slice := arrayPtr[0:length:length]

    fmt.Printf("Direct slice type %v
", reflect.TypeOf(slice))
    //Print 3: Direct type []main._Ctype_uchar
}

How could I do to recover an []uint8 instead of []main._Ctype_uchar with the second solution? Or do you have another solution to do that without a bytes copy?

  • 写回答

1条回答 默认 最新

  • dongzhenshen7435 2018-11-07 07:53
    关注

    Sorry guys, I found my own mistake:

    // convert unsafePtr to a pointer of the type *[1 << 30]C.uint8_t
    arrayPtr := (*[1 << 30]C.uint8_t)(unsafePtr)
    

    ==> to

    // convert unsafePtr to a pointer of the type *[1 << 30]uint8
    arrayPtr := (*[1 << 30]uint8)(unsafePtr)
    

    Problem solved!

    Thanks ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退