zoukankan      html  css  js  c++  java
  • ProtoBuffer 简单例子

    最近学了一下protobuf,写了一个简单的例子,如下:

    person.proto文件

    [cpp] view plain copy
     
    1. message Person{  
    2.     required string name = 1;  
    3.     required int32 age = 2;  
    4.     optional string email = 3;  
    5.     enum PhoneType{   
    6.         MOBILE = 1;  
    7.         HOME = 2;  
    8.         WORK = 3;  
    9.     }  
    10.     message Phone{  
    11.         required int32 id = 1;  
    12.         optional PhoneType type = 2 [default = HOME];  
    13.     }  
    14.     repeated string phoneNum = 4;  //对应于cpp的vector  
    15. }  
    安装好protoc以后,执行protoc person.proto --cpp_out=. 生成 person.pb.h和person.pb.cpp

    写文件(write_person.cpp):

    [cpp] view plain copy
     
    1. #include <iostream>  
    2. #include "person.pb.h"  
    3. #include <fstream>  
    4. #include <string>  
    5.   
    6. using namespace std;  
    7.   
    8. int main(){  
    9.     string buffer;  
    10.     Person person;  
    11.     person.set_name("chemical");  
    12.     person.set_age(29);  
    13.     person.set_email("ygliang2009@gmail.com");  
    14.     person.add_phonenum("abc");  
    15.     person.add_phonenum("def");  
    16.     fstream output("myfile",ios::out|ios::binary);  
    17.     person.SerializeToString(&buffer); //用这个方法,通常不用SerializeToOstream  
    18.     output.write(buffer.c_str(),buffer.size());  
    19.     return 0;  
    20. }  
    编译时要把生成的cpp和源文件一起编译,如下:g++ write_person.cpp person.pb.cpp -o write_person -I your_proto_include_path -L your_proto_lib_path -lprotoc -lprotobuf运行时记得要加上LD_LIBRARY_PATH=your_proto_lib_path

    读文件(read_person.cpp):

    [cpp] view plain copy
     
    1. #include <iostream>  
    2. #include "person.pb.h"  
    3. #include <fstream>  
    4. #include <string>  
    5.   
    6. using namespace std;  
    7.   
    8. int main(){  
    9.     Person *person = new Person;  
    10.     char buffer[BUFSIZ];  
    11.     fstream input("myfile",ios::in|ios::binary);  
    12.     input.read(buffer,sizeof(Person));  
    13.     person->ParseFromString(buffer);  //用这个方法,通常不用ParseFromString  
    14.     cout << person->name() << person->phonenum(0) << endl;  
    15.     return 0;  
    16. }  
    编译运行方法同上:g++ read_person.cpp person.pb.cpp -o read_person -I your_proto_include_path -L your_proto_lib_path -lprotoc -lprotobuf
     
  • 相关阅读:
    32-3题:LeetCode103. Binary Tree Zigzag Level Order Traversal锯齿形层次遍历/之字形打印二叉树
    32-1题:不分行从上到下打印二叉树/BFS/deque/queue
    第31题:LeetCode946. Validate Stack Sequences验证栈的序列
    第30题:LeetCode155. Min Stack最小栈
    第29题:LeetCode54:Spiral Matrix螺旋矩阵
    第28题:leetcode101:Symmetric Tree对称的二叉树
    第27题:Leetcode226: Invert Binary Tree反转二叉树
    第26题:LeetCode572:Subtree of Another Tree另一个树的子树
    第25题:合并两个排序的链表
    第24题:反转链表
  • 原文地址:https://www.cnblogs.com/mfryf/p/5263013.html
Copyright © 2011-2022 走看看