简体   繁体   English

协议缓冲区如何支持std容器的序列化/反序列化?

[英]How can protocol-buffers support serialization/deserialization of std containers?

We plan to replace Boost.serialization with protocol-buffers used in distributed system design. 我们计划用分布式系统设计中使用的协议缓冲区替换Boost.serialization How protocol-buffers support complicated data structures such as std containers? 协议缓冲区如何支持复杂的数据结构,如std容器?

For instance, such a class is required to be serialized/deserialized in our case: 例如,在我们的例子中,需要对这样的类进行序列化/反序列化:

class Foo
{
  std::vector< std::pair< unsigned int, std::vector< std::pair< int, int> > > > data;
};

Protocol buffers have employ a parser which takes a .proto file and creates appropriate serialization routines. 协议缓冲区采用了一个解析器,它接受.proto文件并创建适当的序列化例程。 See this . 看到这个

Update: You can represent a vector of strings as: 更新:您可以将字符串向量表示为:

message MyCollection {   
   repeated string str = 1;
} 

in your proto file. 在您的proto文件中。

and use: 并使用:

std::vector<std::string> my_strings; 
// add strings to vector MyCollection proto; 
vector<string>::iterator e = my_strings.end();
for (vector<string>::iterator i = my_strings.begin(); 
    i != e; 
    ++i) {
   *proto.add_str() = *i; 
}

It should be easy to extend for another collection/collection of collections. 它应该很容易扩展到另一个集合/集合集合。

The protobuf representation of your Foo would look something like this: 你的Foo的protobuf表示看起来像这样:

message IntPair {
    required int32 first  = 1;
    required int32 second = 2;
};

message FooElem {
    required uint32 first = 1;
    repeated IntPair second = 2;
};

message Foo {
    repeated FooElem data = 1;
};

Note that Protocol Buffers doesn't provide a "seamless" (de)serialization to/from your own structures like Boost.Serialization does. 请注意,协议缓冲区不会像Boost.Serialization那样为您自己的结构提供“无缝”(de)序列化。 You work with generated objects that come from running the protoc compiler on a file like the above. 您可以使用在上述文件上运行protoc编译器生成的生成对象。

These generated classes will not contain std::pair and std::vector members however, so you'll need to copy data too/from the generated objects if you want to keep working with your legacy Foo structure. 但是,这些生成的类将不包含std::pairstd::vector成员,因此如果您希望继续使用旧的Foo结构,则还需要从生成的对象中复制数据。

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

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