英文:
How to mmap a slice of X in Go?
问题
我正在尝试使用launchpad.net/gommap
来内存映射一个int32
数组和其他自定义的结构体类型。我严格要求在映射区域中使用它们。gommap.Mmap
类型是[]byte
,我该如何将其中的部分作为其他类型的切片使用呢?
英文:
I'm trying to use launchpad.net/gommap
to memory map an array of int32
, and some other custom struct types. I strictly want to use them where they are in the mapped region. The gommap.Mmap
type is []byte
, how can I make sections of that available as slices of some other type?
答案1
得分: 1
你需要使用unsafe包。
func mapInt32(fd uintptr, prot gommap.ProtFlags, flags gommap.MapFlags) ([]int32, error) {
mmap, err := gommap.Map(fd, prot, flags)
if err != nil {
return nil, err
}
header := (*reflect.SliceHeader)(unsafe.Pointer(&mmap))
// 考虑byte和int32之间的大小差异
header.Len /= 4
header.Cap = header.Len
return *(*[]int32)(unsafe.Pointer(header)), nil
}
当你使用完内存后,你可能想要取消映射内存的方式。你可以通过将[]int32
不安全地转换回gommap.MMap
来实现类似的操作。
英文:
You'd have to use the unsafe package.
func mapInt32(fd uintptr, prot gommap.ProtFlags, flags gommap.MapFlags) ([]int32, error) {
mmap, err := gommap.Map(fd, prot, flags)
if err != nil {
return nil, err
}
header := (*reflect.SliceHeader)(unsafe.Pointer(&mmap))
// account for the size different between byte and int32
header.Len /= 4
header.Cap = header.Len
return *(*[]int32)(unsafe.Pointer(header)), nil
}
You may want to make a way to unmap the memory when you're done with it. You could do that by unsafely casting your []int32
back to a gommap.MMap
in a similar way.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论