Take the 2-minute tour ×

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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
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? –  Matt Joiner Aug 6 '13 at 15:35
You could divide header.Cap too. One way or another it should be equal to header.Len. –  Evan Shaw Aug 6 '13 at 22:10
Thanks! That's the clarification I needed. I'll try this answer and mark it the solution if it works. –  Matt Joiner Aug 7 '13 at 2:10

Your Answer


