我正在尝试在共享内存中创建一个 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;
}
最佳答案
MapViewOfFile()
将共享内存映射到进程的地址空间。从那时起(直到它被取消映射)你可以把它当作你分配的(或在堆栈上声明的)本地内存块。
共享内存句柄 hSlots
的大小为 10 * sizeof(int)
字节,如果您真的要在此内存中存储整数,那么最简单的做法是将 pSlots
声明为 int*
:
int* pSlots = reinterpret_cast<int*>( MapViewOfFile(hSlots, FILE_MAP_ALL_ACCESS, 0, 0, 10 * sizeof(int)) );
if (pSlots)
{
// pSlots can now be used as an array
for (int i = 0; i < 10; i++)
{
pSlots[i] = i; // etc etc
}
}
关于C++ WIN32 在共享内存中创建整数和 bool 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18999856/