What does (*[1 << 30]C.YourType) do exactly in CGo?

南笙酒味 提交于 2019-11-29 08:52:38
JimB

*[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.

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]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!