0
我想在共享內存中創建一個int數組和布爾值數組。到目前爲止,我有下面的代碼運行沒有錯誤,'顯然'創建內存,但我不知道我可以使用LPCTSTR訪問數據像一個數組?有人可以請解釋最好的方式去做這件事,因爲我覺得MSDN相當缺乏和痛苦。C++ WIN32在共享內存中創建一個整數和布爾值數組
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;
}
文件映射相對於一些'int'和'bool',然後將返回的指針轉換爲'LPTSTR'? – msam
爲什麼你使用顯式轉換而不是'INVALID_HANDLE_VALUE'? – Medinoc
我的錯誤,我試圖轉換並遵循MSDN文章。 – T3CHN0CR4T