英文:
Converting a pointer to an array in Go
问题
这个问题类似于这个问题,只是我想将指针和长度转换为固定大小的 Golang 数组。
对于切片,解决方案是创建一个包含相关信息的结构体,并直接进行类型转换,代码如下:
// 切片的内存布局
var sl = struct {
addr uintptr
len int
cap int
}{addr, length, length}
// 使用 unsafe 将 sl 转换为 []byte。
b := *(*[]byte)(unsafe.Pointer(&sl))
那么,如何为指定的内存创建一个数组呢?
英文:
This question is similar to this one, only I want to convert a pointer and a length to a fixed-size Golang array.
For a slice, the solution was to create a struct with the relevant information, and cast it directly, as follows:
// Slice memory layout
var sl = struct {
addr uintptr
len int
cap int
}{addr, length, length}
// Use unsafe to turn sl into a []byte.
b := *(*[]byte)(unsafe.Pointer(&sl))
How would you create an array for that specified memory instead?
答案1
得分: 2
与切片类似,但由于Go数组只是按顺序排列的值,而不是像切片那样由指针、容量和长度表示,所以您不需要定义数组的内存布局。
package main
import (
"fmt"
"reflect"
"unsafe"
)
var data = []byte(`foobar`)
func main() {
rv := reflect.ValueOf(data)
ptr := rv.Pointer()
b := *(*[3]byte)(unsafe.Pointer(ptr))
fmt.Printf("%T %q\n", b, b)
}
链接:https://play.golang.org/p/r9yi9OdDIC
英文:
It's almost the same as with slices but since Go arrays are just values laid out sequentially
as opposed to being represented by a pointer
, cap
, and len
like slices are, you don't need to define the array's memory layout.
package main
import (
"fmt"
"reflect"
"unsafe"
)
var data = []byte(`foobar`)
func main() {
rv := reflect.ValueOf(data)
ptr := rv.Pointer()
b := *(*[3]byte)(unsafe.Pointer(ptr))
fmt.Printf("%T %q\n", b, b)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论