Programmdude
Programmdude

Reputation: 541

Remap MapViewOfFile while keeping the same address

The underlying problem I wish to solve is to have two regions of virtual memory that is backed by physical memory (ie, VirtualAlloc), and a third region of virtual memory that "points" to one of the other two regions of virtual memory.

While I believe you can map one of the two backed regions of memory with MapViewOfFileEx, I can't find any way of ensuring that the lpBaseAddress doesn't get stolen when changing the mapping from one region to another region.

My initial idea was to VirtualAlloc with MEM_RESERVE, but MapViewOfFileEx can't use reserved memory.

I believe I can accomplish the same thing on posix with shm_open and family, as mmap can override mapped regions.

Upvotes: 1

Views: 535

Answers (1)

Rita Han
Rita Han

Reputation: 9700

You can't directly override the address if it is in use.

To use the same address (mappedAddress) you need call UnmapViewOfFile before remap. Something like this:

HANDLE targetFile = CreateFile(L"target.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
HANDLE fileMap = CreateFileMapping(targetFile, 0, PAGE_READWRITE, 0, 10, L"myTestMap");
LPVOID mappedAddress = MapViewOfFileEx(fileMap, FILE_MAP_ALL_ACCESS, 0, 0, 0, 0);
BOOL result = UnmapViewOfFile(mappedAddress); // Get the address.

HANDLE targetFile2 = CreateFile(L"target2.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
HANDLE fileMap2 = CreateFileMapping(targetFile2, 0, PAGE_READWRITE, 0, 10, L"myTestMap2");
LPVOID mappedAddress2 = MapViewOfFileEx(fileMap2, FILE_MAP_ALL_ACCESS, 0, 0, 0, mappedAddress); // Use the same address.

Upvotes: 3

Related Questions