问题描述
在 Golang wiki 中的Turning C arrays into Go slices"下,有是一段代码,用于演示如何创建由 C 数组支持的 Go 切片.
导入C"导入不安全"...var theCArray *C.YourType = C.getTheArray()长度 := C.getTheArrayLength()切片 := (*[1 << 30]C.YourType)(unsafe.Pointer(theCArray))[:length:length]
谁能解释一下 (*[1 << 30]C.YourType)
到底是做什么的?它如何将 unsafe.Pointer
变成 Go 切片?
*[1 <<30]C.YourType
本身不做任何事情,它是一个类型.具体来说,它是一个指向大小为 1 ,
C.YourType
值.大小是任意的,仅表示需要在主机系统上有效的上限.
您在第三个表达式中所做的是类型转换.这会将 unsafe.Pointer
转换为 *[1 <<30]C.YourType
.
然后,您将转换后的数组值转换为带有 完整切片的切片表达式(切片表达式不需要取消对数组值的引用,因此即使它是一个指针,也不需要为该值添加前缀*
).>
你可以像这样扩展它:
//unsafe.Pointer to the C arrayunsafePtr := unsafe.Pointer(theCArray)//将 unsafePtr 转换为 *[1 <<30]C.你的类型arrayPtr := (*[1 << 30]C.YourType)(unsafePtr)//将数组切片为 Go 切片,具有相同的后备数组//作为CArray,确保指定容量以及//长度.切片 := arrayPtr[:length:length]
In the Golang wiki, under "Turning C arrays into Go slices", there is a block of code that demonstrates how to create a Go slice backed by a C array.
import "C"
import "unsafe"
...
var theCArray *C.YourType = C.getTheArray()
length := C.getTheArrayLength()
slice := (*[1 << 30]C.YourType)(unsafe.Pointer(theCArray))[:length:length]
Can anyone explain exactly what (*[1 << 30]C.YourType)
does? How does it turn an unsafe.Pointer
into a Go slice?
*[1 << 30]C.YourType
doesn't do anything itself, it's a type. Specifically, it's a pointer to an array of size 1 << 30
, of C.YourType
values. The size is arbitrary, and only represents an upper bound that needs to be valid on the host system.
What you're doing in the third expression is a type conversion.This converts the unsafe.Pointer
to a *[1 << 30]C.YourType
.
Then, you're taking that converted array value, and turning it into a slice with a full slice expression (Array values don't need to be dereferenced for a slice expression, so there is no need to prefix the value with a *
, even though it is a pointer).
You could expand this out a bit like so:
// unsafe.Pointer to the C array
unsafePtr := unsafe.Pointer(theCArray)
// convert unsafePtr to a pointer of the type *[1 << 30]C.YourType
arrayPtr := (*[1 << 30]C.YourType)(unsafePtr)
// slice the array into a Go slice, with the same backing array
// as theCArray, making sure to specify the capacity as well as
// the length.
slice := arrayPtr[:length:length]
这篇关于(*[1 << 30]C.YourType) 在 CGo 中究竟做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!