【发布时间】:2009-10-12 10:28:49
【问题描述】:
我想读取应用程序通过共享内存提供的状态信息。我想使用 C++ 来读取该命名共享内存的内容,然后使用来自 C# 类的 pinvoke 调用它。
从软件我知道它有一定的文件结构:一个结构体STATUS_DATA,其中包含四个结构体SYSTEM_CHARACTERISTICS的数组。
我(还)不熟悉 C++,所以我基本上尝试遵循 msdn。为了找到要映射的文件的大小,我添加了结构成员的大小,如下面的代码所示。这导致访问被拒绝,所以我认为基于结构的结果太高了。当我使用sizeof(STATUS_DATA)(我将结构添加到我的源代码)时,它仍然以拒绝访问结束。如果我尝试更低的值,比如 1024 字节,那么在调试时我在pbuf 中只能看到<。
这是我目前得到的:
#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;
}
我还通过关注hint 来确保此共享内存“存在”。有人可以给我一个提示,我错过了什么吗?谢谢!
【问题讨论】:
标签: c++ windows shared-memory