c - 直接C指针转换

标签 c pointers go type-conversion cgo

我有这个 C 代码:

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

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

在 GO 代码中,我试图将 data 指针用作 GO 数组或 slice ,我想从 *C.uint8_t 中检索一个 []uint8。我知道 data

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

    fmt.Printf("Data type %v\n", 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\n", 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\n", reflect.TypeOf(slice))
    //Print 3: Direct type []main._Ctype_uchar
}

如何使用第二种解决方案恢复 []uint8 而不是 []main._Ctype_uchar?或者您是否有另一种解决方案可以在没有字节副本的情况下做到这一点?

最佳答案

对不起各位,我发现了自己的错误:

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

==> 到

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

问题解决了!

谢谢;)

关于c - 直接C指针转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53185257/

相关文章:

c - 指针上的字符串 scanf

go - metadata.FromOutgoingContext 和 metadata.FromIncomingContext 有什么区别?

go - 乘以 *float32 和 int 值

c - 释放函数内部的指针,并在 main 中使用它

c - 将指针数组转换为数组

go - 有 time.Sleep() 的无限循环与没有 time.Sleep() 的无限循环

c++ - 将 (size_t)-1 传递给 snprintf_s

c - 具有相同类型字段的结构上的 MPI_Allreduce 是否可移植?

c - 确定内存中指针的字节数

c++ - 制作一个像流一样的 C++ 宏