c++protocol-bufferscapnproto

How to access serialized data of Cap'n'Proto?


I'm working with Cap'n'Proto and my understanding is there is no need to do serialization as it's already being done. So my question is, how would I access the serialized data and get it's size so that I can pass it in as a byte array to another library.

// person.capnp
struct Person {
    name @0 :Text;
    age @1 :Int16;
}

// ...
::capnp::MallocMessageBuilder message;

Person::Builder person = message.initRoot<Person>();
person.setName("me");
person.setAge(20);

// at this point, how do I get some sort of handle to 
// the serialized data of 'person' as well as it's size?

I've seen the writePackedMessageToFd(fd, message); call, but didn't quite understand what was being passed and couldn't find any API docs on it. I also wasn't trying to write to a file descriptor as I need the serialized data returned as const void*.

Looking in Capnproto's message.h file is this function which is in the base class for MallocMessageBuilder which says it gets the raw data making up the message.

kj::ArrayPtr<const kj::ArrayPtr<const word>> getSegmentsForOutput();
// Get the raw data that makes up the message.

But even then, Im' not sure how to get it as const void*.

Thoughts?


Solution

  • This appears to be whats needed.

    // ...
    ::capnp::MallocMessageBuilder message;
    
    Person::Builder person = message.initRoot<Person>();
    person.setName("me");
    person.setAge(20);
    
    kj::Array<capnp::word> dataArr = capnp::messageToFlatArray(message);
    kj::ArrayPtr<kj::byte> bytes = dataArr.asBytes();
    
    std::string data(bytes.begin(), bytes.end());
    
    const void* dataPtr = data.c_str();
    

    At this point, I have a const void* dataPtr and size using data.size().