问题描述
在中的将C数组转换为Go片下,有一段代码演示了如何创建一个由C数组支持的Go slice。
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]
任何人都可以准确解释(* [1 的含义吗?它如何将一个
unsafe.Pointer
变成一个Go切片?
Can anyone explain exactly what (*[1 << 30]C.YourType)
does? How does it turn an unsafe.Pointer
into a Go slice?
推荐答案
* [1 本身不做任何事情,它是一种类型。具体来说,它是一个指向大小
1 ,
C.YourType
值。
*[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.
您在第三个表达式是。
这将 unsafe.Pointer
转换为 * [1<< 30] C.YourType
。
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[0:length:length]
这篇关于(* [1 <30] C.YourType)在CGo中做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!