转到由C数组支持的切片 [英] Go slice backed by a C array
数组大小 1<<30
,必须大于或等于 length
变量的任何值.
程序包主要进口 ("fmt"不安全")func main(){输入YourType字节theCArray:=& [8] YourType {}const arrayLen = 1<<30{长度:= arrayLenfmt.Println()fmt.Println(arrayLen,长度)fmt.Println()slice:=(* [arrayLen] YourType)(unsafe.Pointer(theCArray))[:length:length]fmt.Println(len(slice),cap(slice),slice [:8])}{长度:= arrayLen + 1fmt.Println()fmt.Println(arrayLen,长度)fmt.Println()//运行时错误:切片范围超出范围slice:=(* [arrayLen] YourType)(unsafe.Pointer(theCArray))[:length:length]fmt.Println(len(slice),cap(slice),slice [:8])}}
游乐场: https://play.golang.org/p/e4jv8jfU_WI >
输出:
<代码> 1073741824 10737418241073741824 1073741824 [0 0 0 0 0 0 0 0]1073741824 1073741825紧急情况:运行时错误:切片范围超出范围goroutine 1 [运行中]:main.main()/tmp/sandbox576164402/main.go:30 + 0x320
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?
解决方案
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
这篇关于转到由C数组支持的切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文