0

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 Answer 1

1

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.

3
  • You've made header.Cap = header.Len, despite the fact those are already equal when gommap.Map returns. Did you do this to avoid doing the division by 4 again? Commented Aug 6, 2013 at 15:35
  • 1
    You could divide header.Cap too. One way or another it should be equal to header.Len.
    – Evan Shaw
    Commented Aug 6, 2013 at 22:10
  • Thanks! That's the clarification I needed. I'll try this answer and mark it the solution if it works. Commented Aug 7, 2013 at 2:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.