在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]有人能解释一下(*[1 << 30]C.YourType)到底是做什么的吗?它如何将unsafe.Pointer转换为Go切片?
发布于 2018-02-13 06:45:01
*[1 << 30]C.YourType本身不做任何事情,它是一种类型。具体地说,它是指向C.YourType值大小为1 << 30数组的指针。大小是任意的,并且仅表示需要在主机系统上有效的上限。
您在第三个表达式中所做的是一个type conversion。这会将unsafe.Pointer转换为*[1 << 30]C.YourType。
然后,获取转换后的数组值,并将其转换为带有full slice expression的片(对于片表达式,不需要解引用数组值,因此不需要在值前加上*,即使它是一个指针)。
你可以像这样扩展一下:
// 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]https://stackoverflow.com/questions/48756732
复制相似问题