我正在嘗試使用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。然而,當我嘗試打印什麼,我認爲應該是值沒有錯誤拋出在地址,我得到一個笑臉......
任何人都可以點我在正確的方向?我有一些懷疑(沒有終止\ 0?),但我真的不明白這裏的內部運作。任何幫助表示讚賞!
嘗試'std :: cout <<「內存值:」<<(int)* mem <<「\ n」;' –
非常感謝! – willpower2727