简体   繁体   English

如何访问 Cap'n'Proto 的序列化数据?

[英]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.我正在与 Cap'n'Proto 合作,我的理解是没有必要进行序列化,因为它已经完成了。 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);我见过writePackedMessageToFd(fd, message); call, but didn't quite understand what was being passed and couldn't find any API docs on it.调用,但不太明白传递的是什么,也找不到任何 API 文档。 I also wasn't trying to write to a file descriptor as I need the serialized data returned as const void* .我也没有尝试写入文件描述符,因为我需要以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.查看 Capnproto 的 message.h 文件是这个函数,它位于 MallocMessageBuilder 的基类中,它表示它获取构成消息的原始数据。

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* .但即便如此,我也不知道如何将它作为const void*

Thoughts?想法?

::capnp::MallocMessageBuilder message;

is your binary message, and its size is是你的二进制消息,它的大小是

message.sizeInWords()

(size in bytes divided by 8). (以字节为单位的大小除以 8)。

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() .在这一点上,我有一个const void* dataPtr和 size 使用data.size()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM