Go slice backed by a C array [duplicate]

风格不统一 提交于 2020-07-08 03:20:49

问题


In the CGO section of the Golang Wiki, there is an article that explains how to create a Go slice backed by a C array. In the article there is a code snipped that details the conversion and most important statement in that snippet is the following:

slice := (*[1 << 30]C.YourType)(unsafe.Pointer(theCArray))[:length:length]

Everything in the statement makes sense to me except the [1 << 30] part. Can you please explain to me why this is needed?


回答1:


The array size, 1 << 30, must be greater than or equal to any value of the length variable.

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    type YourType byte
    theCArray := &[8]YourType{}
    const arrayLen = 1 << 30

    {
        length := arrayLen

        fmt.Println()
        fmt.Println(arrayLen, length)
        fmt.Println()
        slice := (*[arrayLen]YourType)(unsafe.Pointer(theCArray))[:length:length]
        fmt.Println(len(slice), cap(slice), slice[:8])
    }

    {
        length := arrayLen + 1

        fmt.Println()
        fmt.Println(arrayLen, length)
        fmt.Println()
        // runtime error: slice bounds out of range
        slice := (*[arrayLen]YourType)(unsafe.Pointer(theCArray))[:length:length]
        fmt.Println(len(slice), cap(slice), slice[:8])
    }
}

Playground: https://play.golang.org/p/e4jv8jfU_WI

Output:

1073741824 1073741824

1073741824 1073741824 [0 0 0 0 0 0 0 0]

1073741824 1073741825

panic: runtime error: slice bounds out of range

goroutine 1 [running]:
main.main()
    /tmp/sandbox576164402/main.go:30 +0x320


来源:https://stackoverflow.com/questions/48812988/go-slice-backed-by-a-c-array

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