[英]Converting a pointer to a byte slice
The Mmap()
syscall in the x/sys/unix
package in Golang returns a []byte
type, while the underlying syscall actually returns a pointer. Mmap()
的x/sys/unix
包中的Mmap()
系统调用返回[]byte
类型,而基础系统调用实际上返回指针。 How does it do this? 它是如何做到的?
More specifically, in this package by a Golang developer, the VirtualAlloc
function simply returns a pointer. 更具体地说,在Golang开发人员的此程序包中,
VirtualAlloc
函数仅返回一个指针。 How can this be converted to a byte slice, the same way as it's done in the Unix package? 如何将其转换为字节片,就像在Unix软件包中一样?
Using the unsafe
package you can do the same thing golang.org/x/sys/unix
does in the Mmap method of its unexported mmapper
type: 使用
unsafe
包,你可以做同样的事情golang.org/x/sys/unix
确实在MMAP其未导出的方法mmapper
类型:
// 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))
Here's a playground example . 这是一个操场的例子 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.