Creating a Memory Maped Object


What is it good for?
Mostly used to share data among processes and to have a faster access to files.
In addition it has no need in allocating new virtual memory and thus saves precious resources.
The first step is creating a memory map of the file, and the second step is to create a view of the map in the virtual memory.

This link shows a benchmark results of using various methods of file access.

More information can be found here

A simple example:


#include <sys\stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
using namespace std;
__int64 FileSize64( const char * szFileName )
{
struct __stat64 fileStat;
int err = _stat64( szFileName, &fileStat );
if (0 != err) return 0;
return fileStat.st_size;
}
char * g_buffer;

int _tmain(int argc, _TCHAR* argv[])
{
const char fileName[] = "alex.c";
long fileSize = (long)FileSize64(fileName);
g_buffer = new char[fileSize];

HANDLE hFile = CreateFileA(fileName, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
HANDLE hFileMapping = CreateFileMapping(hFile, 0, PAGE_READONLY, 0, fileSize, 0);

int iPos = 0;
const unsigned int BlockSize = 128 * 1024;

while(iPos < fileSize)
{
int iLeft = fileSize - iPos;
int iBytesToRead = iLeft > BlockSize ? BlockSize: iLeft;

void *rawBuffer = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, iPos, iBytesToRead);
memcpy(&g_buffer[iPos], rawBuffer, iBytesToRead);
UnmapViewOfFile(rawBuffer);

iPos += iBytesToRead;
}

CloseHandle(hFileMapping);
CloseHandle(hFile);
printf("%s", g_buffer);

system("pause");
return 0;
}



Post a Comment

Previous Post Next Post