Zubair-Safenet
Zubair-Safenet

Reputation: 141

C++ Boost how to serialize a C++ object to Shared Memory and recreate it in another application

I am going to use boost shared memory and I want to copy my C++ object to this memory. Let's say I have a c++ class

class myobj
{
   public:
      std::string name1;
      int name1Length;
      std::string name2;
      int name2Length
};

I create an object of this class myobj obj;

Let's say I have name1 as "Name1" and the length is 5 and name2 as "Name2" and the length is 5.

I have a shared memory which is created using boost library

            shared_memory_object shm(open_only, "SharedMemory", read_write);

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

I want to copy my c++ object obj to this memory so that I can recreate the same object in another application.

Upvotes: 2

Views: 1366

Answers (1)

sehe
sehe

Reputation: 392999

That seems like a roundabout way (why not use a file?).

Here's a demo using a Boost Interprocess bufferstream:

#include <boost/serialization/string.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/streams/bufferstream.hpp>

class myobj
{
   public:
      std::string name1;
      int name1Length;
      std::string name2;
      int name2Length;

   private:
      friend class boost::serialization::access;
      template <typename Ar> void serialize(Ar& ar, unsigned) { ar & name1 & name1Length & name2 & name2Length; }
};

namespace bip = boost::interprocess;

void do_save() {
    bip::shared_memory_object shm(bip::create_only, "SharedMemory", bip::read_write);

    shm.truncate(10u<<20); // 10MiB
    bip::mapped_region region(shm, bip::read_write); 

    bip::bufferstream bs(std::ios::out);
    bs.buffer(reinterpret_cast<char*>(region.get_address()), region.get_size());
    boost::archive::text_oarchive oa(bs);

    {
        myobj obj;
        obj.name1 = "name the first";
        obj.name2 = "name the second";
        obj.name1Length = obj.name1.length(); // why?
        obj.name2Length = obj.name2.length(); // why?

        oa << obj;
    }
}

myobj do_load() {
    bip::shared_memory_object shm(bip::open_only, "SharedMemory", bip::read_only);
    bip::mapped_region region(shm, bip::read_only); 

    bip::bufferstream bs(std::ios::in);
    bs.buffer(reinterpret_cast<char*>(region.get_address()), region.get_size());
    boost::archive::text_iarchive ia(bs);

    {
        myobj obj;
        ia >> obj;

        return obj;
    }
}

#include <iostream>
int main() {
    do_save();
    auto obj = do_load();
    std::cout << "obj.name2: " << obj.name2 << "\n";
}

Upvotes: 1

Related Questions