Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

cgo

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]

Can anyone explain exactly what (*[1 << 30]C.YourType) does? How does it turn an unsafe.Pointer into a Go slice?

like image 470
Some Noob Student Avatar asked Feb 12 '18 22:02

Some Noob Student


1 Answers

*[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. The size is arbitrary, and only represents an upper bound that needs to be valid on the host system.

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[:length:length]

This construct has been replaced by a generalized unsafe.Slice function in go1.17:

slice := unsafe.Slice(theCArray, length)
like image 98
JimB Avatar answered Nov 16 '22 20:11

JimB