2016-04-27 58 views
1

我正在嘗試使用boost的共享內存庫來執行一些進程間通信(VS 2015)。我發現一個example online這是非常有幫助的。爲了理智,我只想執行一個簡單的檢查,即我寫入共享內存地址的值是我想要的值。爲此,我想用cout打印共享內存的值。這是代碼我目前:打印共享內存地址值到命令行

#include <boost\interprocess\shared_memory_object.hpp> 
#include <boost\interprocess\mapped_region.hpp> 
#include <iostream> 
#include <stdio.h> 
#include <conio.h> 
#include <cstring> 
#include <cstdlib> 
#include <string> 

int main() 
{ 
    using namespace boost::interprocess; 

    struct shm_remove 
    { 
     shm_remove() { shared_memory_object::remove("MySharedMemory"); } 
     ~shm_remove() { shared_memory_object::remove("MySharedMemory"); } 
    } remover; 

    //Create a shared memory object 
    shared_memory_object shm(create_only, "MySharedMemory", read_write); 

    //Set size to 1 
    shm.truncate(1); 

    //Map the whole shared memory in this process 
    mapped_region region(shm, read_write); 

    //Write all the memory to 1 
    std::memset(region.get_address(), 1, region.get_size()); 

    //Check that memory was initialized to 1 
    char *mem = static_cast<char*>(region.get_address()); 

    for (std::size_t i = 0; i < region.get_size(); ++i) 
    { 
     std::cout << "Memory value: " << *mem << "\n"; 
     if (*mem++ != 1) 
     { 
      return 1; //Error checking memory 
     } 
    } 
    std::cout << "press any key to quit"; 
    _getch(); 
} 

的代碼工作正常,當檢查該映射的內存已被設置爲1。然而,當我嘗試打印什麼,我認爲應該是值沒有錯誤拋出在地址,我得到一個笑臉......

enter image description here

任何人都可以點我在正確的方向?我有一些懷疑(沒有終止\ 0?),但我真的不明白這裏的內部運作。任何幫助表示讚賞!

+1

嘗試'std :: cout <<「內存值:」<<(int)* mem <<「\ n」;' –

+0

非常感謝! – willpower2727

回答

3

int明確,那麼std::cout是要輸出的值作爲一個數字,而不是與存儲在mem ASCII碼(可能是不可打印或查找信有趣的是,後者是你的情況)。

請參閱cout not printing unsigned char以獲得有關該問題的更全面的答案。

+0

感謝您的解釋! – willpower2727

2

控制檯向您顯示內存中字節的ASCII表示。任何13歲以下的人物通常都是不可打印的。試試內存演員mem設定成類似67

+0

你是對的,它打印字節的ASCII代表,我用67測試,它打印「C.」。 +1但是我一直在尋找1,我並沒有意識到我想要得到的是什麼。謝謝! – willpower2727

+0

A是65,B是66所以67 = C很棒!你的代碼工作正常:) –