Memory Mapped I/O Gregory Mortensen CSIS 4330, Advanced Windows Programming – UVSC
Implementing Memory Mapped I/O 1.Create or Open the File Object (see lecture 5). 2.Create the Memory Mapped Object 3.Create a view to map the object into your address space
Memory Mapped I/O 2. Create the Memory Mapped Object HANDLE CreateFileMapping (HANDLE hFile, psa, DWORD protect, DWORD maxSizeHigh, DWORD maxSizeLow PCTSTR optionalName) Protect is PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, SEC_RESERVE or SEC_COMMIT, for 2000 also SEC_NOCACHE, or PAGE_NOCACHE, SEC_IMAGE. If maxSizeLow and msHi are both 0, it opens the file at its current size, but appends fail. optionalName is used if the Memory Mapped object is shared between processes.
Memory Mapped I/O 3. Create a view PVOID MapViewOfFileObject (HANDLE hFMObject, DWORD access, DWORD highOffset, DWORD lowOffset,SIZE_T numBytes) Access= FILE_MAP_WRITE, FILE_MAP_READ, or FILE_MAP_COPY(F_M_C the hFMObject must be created with PAGE_WRITE_COPY – WIN98) All zeros for hOffset, lOffset and numBytes maps the whole file
Coherency If the view is created with access FILE_MAP_COPY, then only the original file is shared between process boundries. Any changes are made to your copy not to the original If the view is create with access FILE_MAP_WRITE then changes made in your process are also made in other processes transparently, by the operating system.
Using Memory Mapped IO without a file Passing INVALID_HANDLE_VALUE (the value returned by a failed CreateFile) creates a memory mapping of the page file and not of a disk file. A simple clipboard could use a memory mapped file of a process’es memory space and not of an actual file.
Preserving Memory By default, when you create a Map Object, the default pageProtection is SEC_COMMIT. To use memory only as you need it: 1. Create with SEC_RESERVE 2. Use PVOID VirtualAlloc(PVOID pvAddress, SIZE_T dwSize, DWORD allocType, DWORD protect) 3. All processes mapped to the object can then access that location successfully!
Relocatability You can use CreateFileMappingEx & CreateMapViewEx to force a Map Object or view to always be forced to an address. This allows you to use pointers freely, (every process would have the Map Object to same the memory address) however if that address is in use, the above creates would fail. To use pointers and guarantee relocatablity you should use relative addressing.
Clean up 1.Close the View: UnmapViewOfFile (PVOID returnedByCreateMapView) 2.Close the File Mapping Object: CloseHandle(MappingObject) 3.Close the File Handle, if using files: CloseHandle(FileObject)