(* [1<< 30] C.YourType)在CGo中的作用是什么?

时间:2018-02-12 22:41:12

标签: go cgo

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切片?

1 个答案:

答案 0 :(得分:6)

*[1 << 30]C.YourType本身并没有做任何事,它只是一种类型。具体来说,它是指向大小为1 << 30C.YourType值的数组的指针。

您在第三个表达式中所做的是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[0:length:length]