How to mmap a slice of X in Go?

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

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.

huangapple
  • 本文由 发表于 2013年8月6日 10:55:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/18071112.html
匿名

发表评论

匿名网友

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

确定