什么是Protocol Buffers?
这是Protocol Buffers主页上的一段代码:
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
} message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
而Protocol Buffers的作用,就是将以上格式的数据类型,自动生成Java, Python, and C++的代码,然后以下一系列代码就可以直接调用了:(C++中)
Person person;
person.set_name("John Doe");
person.set_id(1234);
person.set_email("jdoe@example.com");
fstream output("myfile", ios::out | ios::binary);
person.SerializeToOstream(&output); fstream input("myfile", ios::in | ios::binary);
Person person;
person.ParseFromIstream(&input);
cout << "Name: " << person.name() << endl;
cout << "E-mail: " << person.email() << endl;
相信所有C++编程者都为定义set,get之类的函数感到烦人过吧,而Google做的就是帮助你省去这些麻烦,构造更利于网络传输的数据结构。
与XML的比较 优势