protobuf 使用说明和各类坑

须要弄一个写结构体的类,想到protubuf,通过各类坑,总结以下,但愿帮助须要到人html

个人proto文件:node

//option optimize_for = LITE_RUNTIME;
message Node{
    required int64 nodeId = 1;
    required string passwd = 2;
    required double x = 3;
    //required double y = 4;
    //required int64 parrendId = 5;
    //required double distendParrent = 6;
}

使用protoc 文件 --cpp_out .  输出.cc 和 .h 文件ios

编译Makefiile( 简单写的):函数

all:
	protoc node.proto --cpp_out .
	g++ main.cpp node.pb.cc `pkg-config --libs --cflags protobuf` -g

测试文件,主要是main.cpp:测试

/*************************************************************************
	> File Name: main.cpp
	> Author: MaShiChuan
	> Mail: 981880785@qq.com
	> Created Time: 2016年12月17日 星期六 11时22分44秒
 ************************************************************************/

#include<iostream>
#include "node.pb.h"
#include <fstream>
using namespace std;
int main(){
    GOOGLE_PROTOBUF_VERIFY_VERSION; 
    fstream fout("d.dat",ios::out|ios::binary);
    Node a;
    a.set_nodeid(3);
    a.set_x(3.3);
    a.set_passwd("33");
    a.SerializeToOstream(&fout); 
    a.set_nodeid(4);
    a.SerializeToOstream(&fout); 
    a.SerializeToOstream(&fout); 
    fout.close();
    fstream fin("d.dat",ios::in|ios::binary);
    string line;
    do{
        Node b;
        getline(fin,line,'@');
        if(line == ""){
            break;
        }
        //cout<<line<<endl;
        //b.ParseFromIstream(&fin);
        b.ParseFromString(line);
        cout<<b.nodeid()<<endl;
        cout<<b.passwd()<<endl;
    }while(!fin.eof());
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
}

使用方法:ui

proto文件中规定好有那些东西须要存储,main.cpp中设置值, 相关函数能够从.cc文件中找找。很少说。google

有关如何序列化和反序列化,参考下面的文档,spa

我遇到的问题是,向文件中写了三个message,想依次读出了来,结果反序列化与序列化不对应,老是读最后一个message..net

ParseFromStream不能用,用 cat data文件打开是有分行的,想用ParseFromString,分行解析,结果仍是不行,code

网上查类许多资料,没说怎么处理,索性把data文件打开看看,od -a  查看以下:

0000000  bs etx dc2 stx   3   3  em   f   f   f   f   f   f  nl   @  bs
0000020 eot dc2 stx   3   3  em   f   f   f   f   f   f  nl   @  bs eot
0000040 dc2 stx   3   3  em   f   f   f   f   f   f  nl   @
0000055

明显有个分割符@,getline函数正好有个输入分隔符的参数,难道要用@分行,而后试了试,发现果真能够。

但愿能帮助须要的人。

参考文档:

入门手册:

http://www.cnblogs.com/stephen-liu74/archive/2013/01/04/2842533.html

类型说明:

http://blog.csdn.net/superbfly/article/details/17920383

参考手册:

http://pages.cs.wisc.edu/~starr/bots/Undermind-src/html/annotated.html

经常使用序列化函数:

http://blog.csdn.net/sealyao/article/details/6940245

相关文章
相关标签/搜索