简体   繁体   English

将指针转换为字节片

[英]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 . 这是一个操场的例子

You could use something like C.GoBytes (eg see here ): 您可以使用C.GoBytes类的C.GoBytes (例如, 参见此处 ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM