将指针转换为数组在Go语言中的实现方式是:

huangapple go评论106阅读模式
英文:

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)
}

https://play.golang.org/p/r9yi9OdDIC

huangapple
  • 本文由 发表于 2017年4月30日 23:51:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/43708273.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定