github.com/fengyoulin/shm@v0.0.0-20200305015033-287e184bdf0a/mapping/windows.go (about) 1 // +build windows 2 3 package mapping 4 5 import ( 6 "golang.org/x/sys/windows" 7 "os" 8 "reflect" 9 "unsafe" 10 ) 11 12 // Mapping of a file 13 type Mapping struct { 14 handle windows.Handle 15 length int 16 addr uintptr 17 } 18 19 // SEC_COMMIT for mapping 20 const SEC_COMMIT = 0x8000000 21 22 // Bytes return mapped memory 23 func (m *Mapping) Bytes() (b []byte) { 24 h := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 25 h.Data = m.addr 26 h.Cap = m.length 27 h.Len = h.Cap 28 return 29 } 30 31 // Create a mapping from a file 32 func Create(file *os.File) (m *Mapping, err error) { 33 info, err := file.Stat() 34 if err != nil { 35 return 36 } 37 size := info.Size() 38 handle, err := windows.CreateFileMapping(windows.Handle(file.Fd()), nil, windows.PAGE_READWRITE|SEC_COMMIT, 0, 0, nil) 39 if err != nil { 40 panic(err) 41 return 42 } 43 addr, err := windows.MapViewOfFile(handle, windows.FILE_MAP_WRITE, 0, 0, 0) 44 if err != nil { 45 _ = windows.CloseHandle(handle) 46 return 47 } 48 m = &Mapping{ 49 handle: handle, 50 length: int(size), 51 addr: addr, 52 } 53 return 54 } 55 56 // Close a mapping 57 func (m *Mapping) Close() (err error) { 58 err = windows.UnmapViewOfFile(m.addr) 59 if e := windows.CloseHandle(m.handle); err == nil { 60 err = e 61 } 62 return 63 }