Created
October 6, 2017 16:09
-
-
Save bblanchon/97c60b8dfc926347da3ad5d1d891ead6 to your computer and use it in GitHub Desktop.
Wrapper class for memory mapped file on Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <experimental/filesystem> | |
#include <windows.h> | |
class MemoryMappedFile { | |
public: | |
using path = std::experimental::filesystem::path; | |
MemoryMappedFile(const path &filename) { | |
_fileHandle = CreateFileW(filename.wstring().c_str(), GENERIC_READ, | |
FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); | |
if (_fileHandle == INVALID_HANDLE_VALUE) { | |
throw std::runtime_error("Failed to open file"); | |
} | |
GetFileSizeEx(_fileHandle, &_size); | |
_mappingHandle = | |
CreateFileMapping(_fileHandle, NULL, PAGE_READONLY, 0, 0, NULL); | |
if (_mappingHandle == NULL) { | |
CloseHandle(_fileHandle); | |
throw std::runtime_error("Failed to create memory mapping"); | |
} | |
_view = MapViewOfFile(_mappingHandle, FILE_MAP_READ, 0, 0, 0); | |
if (_view == NULL) { | |
CloseHandle(_mappingHandle); | |
CloseHandle(_fileHandle); | |
throw std::runtime_error("Failed to map file"); | |
} | |
} | |
~MemoryMappedFile() { | |
UnmapViewOfFile(_view); | |
CloseHandle(_mappingHandle); | |
CloseHandle(_fileHandle); | |
} | |
const void *data() const { return _view; } | |
size_t size() const { return _size.QuadPart; } | |
private: | |
HANDLE _fileHandle; | |
HANDLE _mappingHandle; | |
const void *_view; | |
LARGE_INTEGER _size; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment