我正在尝试在共享内存中创建一个 int 数组和一个 bool 数组。到目前为止,我有以下代码运行没有错误并且“显然”创建了内存,但是我不确定我是否可以使用 LPCTSTR 像数组一样访问数据?有人可以解释一下解决这个问题的最佳方法,因为我发现 MSDN 非常缺乏和痛苦。
void createSharedMemory()
{
const char slotsName[]="Slots";
const char flagsName[]="Flags";
const LONG BufferSize = sizeof(int);
const LONG Buffers = 10;
const LONG FlagSize = sizeof(bool);
HANDLE hSlots = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, 0, BufferSize * Buffers, SLOTSNAME);
assert(hSlots != NULL);
HANDLE hFlags = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, 0, FlagSize * Buffers, flagsName);
assert(hSlots != NULL);
std::cout << "Created shared memory!" << std::endl;
}
int main(int argc, char* argv[])
{
createSharedMemory();
HANDLE hSlots;
LPCTSTR pSlots;
hSlots = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, SLOTSNAME);
if(hSlots == NULL)
{
std::cout << "Could not open slots file mapping object:" << GetLastError() << std::endl;
getchar();
return 0;
}
pSlots = (LPTSTR) MapViewOfFile(hSlots, FILE_MAP_ALL_ACCESS, 0, 0, 10 * sizeof(int));
if(pSlots == NULL)
{
std::cout << "Could not map view of slots file:" << GetLastError() << std::endl;
CloseHandle(hSlots);
getchar();
return 0;
}
std::cout << "Mapped slots correctly!" << std::endl;
HANDLE hFlags;
LPCTSTR pFlags;
hFlags = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, FLAGSNAME);
if(hFlags == NULL)
{
std::cout << "Could not open flags file mapping object:" << GetLastError() << std::endl;
getchar();
return 0;
}
pFlags = (LPTSTR) MapViewOfFile(hFlags, FILE_MAP_ALL_ACCESS, 0, 0, 10 * sizeof(bool));
if(pFlags == NULL)
{
std::cout << "Could not map view of flags file:" << GetLastError() << std::endl;
CloseHandle(hFlags);
getchar();
return 0;
}
std::cout << "Mapped flags correctly!" << std::endl;
//Access the data here
getchar();
UnmapViewOfFile(pSlots);
CloseHandle(hSlots);
UnmapViewOfFile(pFlags);
CloseHandle(hFlags);
return 0;
}