views:

465

answers:

4

I'd like to write to shared memory and then dump the contents to a file in the win32 api. Currently I have this code:

HANDLE hFile, hMapFile;
  LPVOID lpMapAddress;

  hFile = CreateFile("input.map",
  GENERIC_READ | GENERIC_WRITE,
  0,
  NULL,
  OPEN_EXISTING,
  FILE_ATTRIBUTE_NORMAL,
  NULL);

  hMapFile = CreateFileMapping(hFile,
  NULL,
  PAGE_READWRITE,
  0,
  0,
  TEXT("SharedObject"));

  lpMapAddress = MapViewOfFile(hMapFile,
  FILE_MAP_ALL_ACCESS,
  0,
  0,
  0);

  sprintf(MapViewOfFile, "<output 1>");

  UnmapViewOfFile(lpMapAddress);
  CloseHandle(hFile);
  CloseHandle(hMapFile);

However, line 31 (the sprintf call) gives the error:

error: cannot convert `void*(*)(void*, DWORD, DWORD, DWORD, DWORD)' 
to `char*' for argument `1' to `int sprintf(char*, const char*, ...)'

I've tried casting the lpMapAddress to LPTSTR, but it has no effect. What am I doing wrong? Or is there a better way to do it?

+7  A: 

In the

sprintf(MapViewOfFile, "<output 1>");

line, you wanted lpMapAddress, not MapViewOfFile. Or (char*)lpMapAddress to be precise.

Michael Krelin - hacker
Now I feel stupid :)
pypmannetjies
+1  A: 

You are trying to write to a regular file. To write to shared memory you should pass INVALID_HANDLE_VALUE to CreateFileMapping. Check out this article for more details.

   TCHAR szName[]=TEXT("Global\\MyFileMappingObject");
   HANDLE hMapFile;
   PVOID pBuf;
   const DWORD BUF_SIZE = 256;

   hMapFile = CreateFileMapping(
                 INVALID_HANDLE_VALUE,    // use paging file
                 NULL,                    // default security 
                 PAGE_READWRITE,          // read/write access
                 0,                       // max. object size 
                 BUF_SIZE,                // buffer size  
                 szName);                 // name of mapping object

   pBuf = MapViewOfFile(hMapFile,   // handle to map object
                        FILE_MAP_ALL_ACCESS, // read/write permission
                        0,                   
                        0,                   
                        BUF_SIZE);           

   TCHAR szMsg[]=TEXT("<output 1>");
   CopyMemory(pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));

   UnmapViewOfFile(pBuf);    
   CloseHandle(hMapFile);
Kirill V. Lyadvinsky
A: 

In sprintf you are passing the address of the function MapViewOfFile. Instead you should pass the mapped memory address.

Naveen
A: 

Answering the "is there a better way to do it?": Take a look at Boost.Interprocess, the section on memory mapping in particular.

Éric Malenfant