The first process calls the CreateFileMapping function to create a file-mapping object and give it the name MyFileMappingObject
. By using the PAGE_READWRITE flag, the processes will have read/write permission to the memory through any file views that are created.
HANDLE hMapFile;
hMapFile = CreateFileMapping(hFile, // Current file handle.
NULL, // Default security.
PAGE_READWRITE, // Read/write permission.
0, // Max. object size.
0, // Size of hFile.
"MyFileMappingObject"); // Name of mapping object.
if (hMapFile == NULL)
{
ErrorHandler("Could not create file-mapping object.");
}
The process then uses the file-mapping object handle returned by CreateFileMapping in the call to MapViewOfFile to create a view of the file in the process's address space. The MapViewOfFile function returns a pointer to the file view.
LPVOID lpMapAddress;
lpMapAddress = MapViewOfFile(hMapFile, // Handle to mapping object.
FILE_MAP_ALL_ACCESS, // Read/write permission
0, // Max. object size.
0, // Size of hFile.
0); // Map entire file.
if (lpMapAddress == NULL)
{
ErrorHandler("Could not map view of file.");
}
The second process calls the OpenFileMapping function with the name MyFileMappingObject
to use the same file-mapping object as the first process. Like the first process, the second process uses the MapViewOfFile function to obtain a pointer to the file view.
HANDLE hMapFile;
LPVOID lpMapAddress;
hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, // Read/write permission.
FALSE, // Do not inherit the name
"MyFileMappingObject"); // of the mapping object.
if (hMapFile == NULL)
{
ErrorHandler("Could not open file-mapping object.");
}
lpMapAddress = MapViewOfFile(hMapFile, // Handle to mapping object.
FILE_MAP_ALL_ACCESS, // Read/write permission.
0, // Max. object size.
0, // Size of hFile.
0); // Map entire file.
if (lpMapAddress == NULL)
{
ErrorHandler("Could not map view of file.");
}