1

I want to read status information that an application provides via shared memory. I want to use C++ in order to read the content of that named shared memory and then call it with pinvoke from a C#-class.

From the software I know that it has a certain file structure: A struct STATUS_DATA with an array of four structs of SYSTEM_CHARACTERISTICS.

I'm not (yet) familiar with C++, so I tried to follow msdn basically. To find the size of the file to be mapped, I added the sizes of the struct members as to be seen in the code below. This results in a ACCESS DENIED, so I figured, that the result based on the structs is too high. When I use sizeof(STATUS_DATA) (I added the struct to my source), it still ends up in an ACCESS DENIED. If I try something lower, like 1024 Bytes, only thing I can see in pbuf is a <, while debugging.

This is what I got so far:

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <iostream>
#pragma comment(lib, "user32.lib")

using namespace std;


signed int BUF_SIZE = 4 * (10368 + 16 + 4 + 16 + 4 + 16 + 4 + 1 + 4); // sizeof(STATUS_DATA);
TCHAR szName[]=TEXT("ENGINE_STATUS");

int main()
{
   HANDLE hMapFile;
   unsigned char* pBuf;

   hMapFile = OpenFileMapping(
                   FILE_MAP_READ,    // read access
                   FALSE,                 // do not inherit the name
                   szName);               // name of mapping object 

   if (hMapFile == NULL) 
   { 
      _tprintf(TEXT("Could not open file mapping object (%d).\n"), 
             GetLastError());

      return 1;
   } 

   pBuf = (unsigned char*) MapViewOfFile(hMapFile, // handle to map object
               FILE_MAP_READ,  // read/write permission
               0,                    
               0,                    
               BUF_SIZE); // 1024);                  

   if (pBuf == NULL) 
   { 
      _tprintf(TEXT("Could not map view of file (%d).\n"), 
             GetLastError()); 

   CloseHandle(hMapFile);
      return 1;
   }

   UnmapViewOfFile(pBuf);

   CloseHandle(hMapFile);

   return 0;
}

I also made sure that this Shared Mem "is there" by following that hint. Can somebody give me a hint, what I'm missing? Thanks!

4

1 回答 1

3

MapViewOfFile (dwNumberOfBytesToMap) 的最后一个参数必须小于创建映射时指定的最大大小。由于我们不知道该大小是多少,因此假设 BUF_SIZE 超过它而 1024 没有似乎是公平的。将此参数指定为 0 是将整个文件映射到单个视图的简单方法。

大多数(全部?)C++ 调试器会假设指向 char 的指针是以空字符结尾的字符串,因此当您尝试查看映射数据时,它只会显示到第一个字节为零。根据文件映射中的数据,这很可能是第二个字节,这解释了为什么您看不到太多信息。您最好将返回的指针转换为 STATUS_DATA* 并查看各个成员。

简而言之:

  • 为 dwNumberOfBytesToMap 指定零 (0)
  • 将返回的指针转换为 STATUS_DATA* 而不是 unsigned char*
于 2009-10-12T11:02:01.483 回答