[英]What does (*[1 << 30]C.YourType) do exactly in 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 << 30]C.YourType
本身不做任何事情,它是一種類型。 具體來說,它是一個指向C.YourType
值的大小為1 << 30
的數組的指針。 大小是任意的,僅表示需要在主機系統上有效的上限。
您在第三個表達式中所做的是類型轉換。 這會將unsafe.Pointer
轉換為*[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[:length:length]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.