在Golang wiki中,在"将C数组转换为Go切片"下,有一段代码,演示了如何创建由C数组支持的Go切片.
import "C"
import "unsafe"
...
var theCArray *C.YourType = C.getTheArray()
length := C.getTheArrayLength()
slice := (*[1 << 30]C.YourType)(unsafe.Pointer(theCArray))[:length:length]
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释究竟是什么(*[1 << 30]C.YourType)
?它如何unsafe.Pointer
变成Go切片?
*[1 << 30]C.YourType
它本身没有做任何事,它是一种类型.具体地讲,它是一个指向大小的数组1 << 30
的,C.YourType
值.
你在第三个表达式中所做的是类型转换.这将转换unsafe.Pointer
为a *[1 << 30]C.YourType
.
然后,您将获取转换后的数组值,并将其转换为具有完整切片表达式的切片(对于切片表达式,不需要取消引用数组值,因此不需要为该值添加前缀*
,甚至是虽然它是一个指针).
您可以将其扩展一下:
// 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[0:length:length]
Run Code Online (Sandbox Code Playgroud)