英文:
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)
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论