2013-09-25 54 views
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; 
} 
+0

文件映射相對於一些'int'和'bool',然後將返回的指針轉換爲'LPTSTR'? – msam

+0

爲什麼你使用顯式轉換而不是'INVALID_HANDLE_VALUE'? – Medinoc

+0

我的錯誤,我試圖轉換並遵循MSDN文章。 – T3CHN0CR4T

回答

5

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 
    } 
} 
+0

完美,正是我所需要的。謝謝:D – T3CHN0CR4T

相關問題