c++serializationmpiprotocol-bufferscapnproto

Cap’n Proto C++ serialize to char array (or any byte array)


My goal is to send serialized data through MPI. I have done this with ProtoBuf but I would like to try to use a faster serialize method such as Cap’n Proto (I will try others as well but here I am stuck). With ProtoBuf I use the function SerializeToArray(void * data, int size) function which works just fine.

Now, I want to do the same thing but with Cap’n Proto but I cannot find anywhere how to do this (if you have a link please send it). Since Cap’n Proto claims to be a faster substitute for ProtoBuf I find this surprising. Maybe, I am going about this the completely wrong way.

So my question becomes:

How do I serialize to char array (or any byte array) with Cap’n Proto (if it is at all possible)? Or how do I serialize in a way which could easily be sent over MPI using C++?


Solution

  • For the message given in this AddrssBook example from documentation, you can do something like this:

    // Documentation: https://capnproto.org/cxx.html
    // AddressBook example
    
    void sendMessage( const char* data, const std::size_t size ); 
    
    void writeAddressBook()
    {
        ::capnp::MallocMessageBuilder message;
    
        auto addressBook = message.initRoot<AddressBook>();
        auto people = addressBook.initPeople(1);
    
        auto alice = people[0];
        alice.setId(123);
        alice.setName("Alice");
        alice.setEmail("alice@example.com");
    
        auto alicePhones = alice.initPhones(1);
        alicePhones[0].setNumber("555-1212");
        alicePhones[0].setType(Person::PhoneNumber::Type::MOBILE);
        alice.getEmployment().setSchool("MIT");
    
        // get char array and send
    
        const auto m = capnp::messageToFlatArray( message );
        const auto c = m.asChars();
        std::cout << c.size() << '\n';
    
        sendMessage( c.begin(), c.size() ); // pass as char array
    }