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
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.
-
You've made
header.Cap = header.Len
, despite the fact those are already equal whengommap.Map
returns. Did you do this to avoid doing the division by 4 again? Commented Aug 6, 2013 at 15:35 -
1You could divide
header.Cap
too. One way or another it should be equal toheader.Len
. 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