proto文件为:
package tutorial;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
用四种方式简单的展示了protobuf序列化和反序列化的例子:
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <fstream>
#include "person.pb.h"
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::ios;
using std::fstream;
using namespace tutorial; //Person的名字空间
/*继承关系为
ios_base <-- ios <-- istream <-- iostream <-- fstream
<-- ostream
*/
void PrintPerson(Person& obj) {
cout << "name: " << obj.name() <<endl;
cout << "id: " << obj.id() <<endl;
cout << "email: " << obj.email() <<endl;
cout << endl << endl;
}
void set_person(char* buf, int& len) {
if (buf == NULL) {
return;
}
Person obj;
obj.set_id(1);
obj.set_name("mike"); //和下面的是两种不同的方式
*obj.mutable_email() = "xxx.com";
len = obj.ByteSize();
obj.SerializeToArray(buf, len); //bool SerializeToArray(void* data, int size) const;
cout << "len is " << len << endl;
}
void get_person(char* buf, int len) { //len是传入,必须要
Person obj;
obj.ParseFromArray(buf, len); //bool ParseFromArray(const void* data, int size);
PrintPerson(obj);
}
void set_person_str(string& str) {
Person obj;
*(obj.mutable_name()) = "shonm";
obj.set_email("xxx@qq.com");
obj.set_id(2);
obj.SerializeToString(&str); //bool SerializeToString(string* output) const;
}
void get_person_str(string& str) {
Person obj;
obj.ParseFromString(str); //bool ParseFromString(const string& data);
PrintPerson(obj);
}
//序列化到文件中去
void set_person_file() {
Person obj;
*(obj.mutable_name()) = "lucy";
obj.set_email("xxx@qq.com");
obj.set_id(3);
int fd = open("./pb.xxx", O_CREAT | O_TRUNC | O_RDWR, 0644);
if (fd <= 0) {
perror("open");
exit(-1);
}
obj.SerializeToFileDescriptor(fd); //bool SerializeToFileDescriptor(int file_descriptor) const;
close(fd);
}
void get_person_file() {
int fd = open("./pb.xxx", O_RDONLY);
if (fd <= 0) {
perror("open");
exit(-1);
}
Person obj;
obj.ParseFromFileDescriptor(fd); //bool ParseFromFileDescriptor(int file_descriptor);
close(fd);
PrintPerson(obj);
}
void set_person_stream() {
Person obj;
obj.set_id(5);
obj.set_name("jack");
*obj.mutable_email() = "xxx@163.com";
std::fstream output("pb2.xxx", ios::out | ios::trunc | ios::binary);
if (! obj.SerializeToOstream(&output)) {
std::cerr << "Failed to write file. " << endl;
return;
}
output.close();
}
void get_person_stream() {
Person obj;
fstream input("./pb2.xxx", ios::in | ios::binary);
obj.ParseFromIstream(&input);
input.close();
PrintPerson(obj);
}
int main()
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
char buf[1024] = {0};
int len = 0;
set_person(buf, len); //len传出
get_person(buf, len); //len引用传入
string str;
set_person_str(str); //传出
get_person_str(str); //引用传入
set_person_file();
get_person_file();
set_person_stream();
get_person_stream();
google::protobuf::ShutdownProtobufLibrary();
return 0;
}