我正在尝试在共享内存中创建一个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;
}
答案 0 :(得分:5)
MapViewOfFile()
将共享内存映射到进程的地址空间。从那时起(直到它被取消映射),您可以将其视为您分配(或在堆栈中声明)的本地内存块。
共享内存句柄hSlots
的大小为10 * sizeof(int)
个字节,如果你真的在这个内存中存储了int,那么最简单的方法是将pSlots
声明为{{ 1}}:
int*