当前位置: > > > > 直接C指针转换
直接C指针转换
来源:stackoverflow
2024-05-01 19:33:35
0浏览
收藏
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天米云给大家整理了《直接C指针转换》,聊聊,我们一起来看看吧!
问题内容
我有这个 c 代码:
uint8_t *data[buf_size]; data = ...; // extern void goreaddata(uint8_t *data, int buffersize); goreaddata(data, buf_size)
在 go 代码中,我尝试使用 data 指针作为 go 数组或切片,我想从 *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指针转换》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注米云公众号吧!
