将指针转换为字节切片

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

Converting a pointer to a byte slice

问题

x/sys/unix包中的Mmap()系统调用在Golang中返回一个[]byte类型,而底层系统调用实际上返回一个指针。它是如何实现的呢?

更具体地说,在这个由Golang开发者创建的中,VirtualAlloc函数只是返回一个指针。如何将其转换为字节切片,就像在Unix包中所做的那样?

英文:

The Mmap() syscall in the x/sys/unix package in Golang returns a []byte type, while the underlying syscall actually returns a pointer. How does it do this?

More specifically, in this package by a Golang developer, the VirtualAlloc function simply returns a pointer. How can this be converted to a byte slice, the same way as it's done in the Unix package?

答案1

得分: 5

使用unsafe包,您可以执行类似于Mmap方法的Unix实现中所做的操作:

type sliceHeader struct {
	addr unsafe.Pointer
	len int
	cap int
}

var b []byte
hdr := (*sliceHeader)(unsafe.Pointer(&b))
hdr.addr = unsafe.Pointer(addr)
hdr.cap = length
hdr.len = length

这里有一个playground示例

英文:

Using the unsafe package you could do something similar to what's being done in the Mmap method's unix implementation:

type sliceHeader struct {
	addr unsafe.Pointer
	len int
	cap int
}

var b []byte
hdr := (*sliceHeader)(unsafe.Pointer(&b))
hdr.addr = unsafe.Pointer(addr)
hdr.cap = length
hdr.len = length

Here's a playground example.

答案2

得分: 5

从Go 1.17开始,你现在可以使用unsafe.Slice

mySlice := unsafe.Slice(ptr, numElements)
英文:

As of Go 1.17, you can now use unsafe.Slice:

mySlice := unsafe.Slice(ptr, numElements)

答案3

得分: 3

你可以使用类似 C.GoBytes 的方法(例如,在这里查看):

// 将 C 数据转换为具有显式长度的 Go []byte
func C.GoBytes(unsafe.Pointer, C.int) []byte
英文:

You could use something like C.GoBytes (e.g. see here):

// C data with explicit length to Go []byte
func C.GoBytes(unsafe.Pointer, C.int) []byte

huangapple
  • 本文由 发表于 2017年4月24日 22:39:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/43591047.html
匿名

发表评论

匿名网友

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

确定