首页 > 代码库 > boost::interprocess::shared_memory_object(1)(基本类型)

boost::interprocess::shared_memory_object(1)(基本类型)

#include <iostream>
#include <boost/interprocess/managed_shared_memory.hpp>
struct pos2d
{
    int x;
    int y;
};
using namespace std;
int main()
{
    //boost::interprocess::shared_memory_object类是按照单个字节的方式读写共享内存,用起来不方便
    boost::interprocess::shared_memory_object::remove("Highscore"); 
    boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "Highscore", 1024);//分配1024字节
    pos2d pos = {1, 1};
    auto ptr = managed_shm.construct<pos2d>("pos2d")(pos); 
    std::pair<pos2d*, std::size_t> p = managed_shm.find<pos2d>("pos2d"); 
    if (p.first) //first是对象的指针,second表示对象的个数
    { 
        std::cout << p.first->x << p.first->y << std::endl; 
        std::cout << p.second << std::endl; 
    }
    getchar();
    return 0;
}