MapViewOfFileEx
Function
HANDLE MapViewOfFileEx(HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap, LPVOID lpBaseAddress);
The MapViewOfFileEx function maps a view of a file mapping object into the address space of the calling process.
Parameters
| Parameter | Description |
|---|---|
hFileMappingObject |
A handle to an open file mapping object. This handle must have been created by the CreateFileMapping function. |
dwDesiredAccess |
The type of access to a file view. This parameter can be one or a combination of the following access rights:
|
dwFileOffsetHigh |
A high-order 32-bit DWORD of the starting offset of the file view in the file mapping. |
dwFileOffsetLow |
A low-order 32-bit DWORD of the starting offset of the file view in the file mapping. |
dwNumberOfBytesToMap |
The number of bytes to map in the file view. If this parameter is 0, the entire file mapping is mapped. |
lpBaseAddress |
The starting address of the mapped view in the calling process's virtual address space. If this parameter is NULL, the system determines where to map the view. |
Return Value
If the function succeeds, the return value is the starting address of the mapped view of the specified file mapping object. If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
MapViewOfFileEx allows you to specify a preferred base address for the mapped view. If lpBaseAddress is not NULL, the system attempts to map the view at that address. If the address is already in use or causes a conflict, the function fails, and GetLastError returns ERROR_INVALID_ADDRESS.
If lpBaseAddress is NULL, the system chooses a suitable address for the mapped view. This is the recommended approach unless you have specific reasons for requesting a particular address.
After you have finished with the mapped view, unmap it by calling the UnmapViewOfFile function.
Example
#include <windows.h>
#include <iostream>
int main() {
// Assume hMapFile is a valid handle to a file mapping object
HANDLE hMapFile = OpenFileMapping(
FILE_MAP_READ, // Request read access
FALSE, // Do not inherit the name
L"MyFileMappingObject"); // Name of the mapping object
if (hMapFile == NULL) {
std::cerr << "Could not open file mapping object." << std::endl;
return 1;
}
LPVOID lpMapView = MapViewOfFileEx(
hMapFile, // Handle to the file mapping object
FILE_MAP_READ, // Read access
0, // High dword of the offset
0, // Low dword of the offset
0, // Map the entire file
NULL); // Let the system choose the address
if (lpMapView == NULL) {
std::cerr << "Could not map view of file. Error: " << GetLastError() << std::endl;
CloseHandle(hMapFile);
return 1;
}
std::cout << "File mapping viewed successfully at address: " << lpMapView << std::endl;
// ... use the mapped memory ...
// Unmap the view and close the handle
UnmapViewOfFile(lpMapView);
CloseHandle(hMapFile);
return 0;
}