一起来看看protobuf中容易引起bug的一个细节

来源:互联网 发布:淘宝直播卖的衣服好么 编辑:程序博客网 时间:2024/05/21 03:25

        我们已经介绍过protobuf的使用了, 故不再赘述, 下面我们来看看如下代码的一个小bug:

        test.proto内容为:

package NS;  message PointReq {      required int32 x=1;      required int32 y=2;  }
       main.cpp为:

#include <iostream>#include <string>using namespace std;#include "test.pb.h"using namespace NS;int main(){    PointReq point;    point.set_x(1);    point.set_y(0);    string tmp;    bool ret = point.SerializeToString(&tmp); // 这里要传地址    if (ret)    {        printf("encode ok!\n");    }    else    {        printf("encode error!\n");return -1;    }// 为了便于网络传输, 这里需要转化成指针式bufferconst char *p = tmp.c_str();string s = p;    PointReq point2;    ret = point2.ParseFromString(s);    if (ret)    {        printf("decode ok, %d, %d\n", point2.x(), point2.y());    }    else    {        printf("decode error!\n");return -2;    }    return 0;}

        结果为:

taoge@localhost Desktop> make cleanrm -fr *.o main    taoge@localhost Desktop> make g++   -c  -L/usr/local/lib   -lprotobuf   -o main.o main.cpp  g++   -c  -L/usr/local/lib   -lprotobuf   -o test.pb.o test.pb.cc g++: -lprotobuf: linker input file unused because linking not doneg++: -lprotobuf: linker input file unused because linking not doneg++    -L/usr/local/lib   -lprotobuf   -o main main.o test.pb.o  taoge@localhost Desktop> ./main encode ok!decode error!taoge@localhost Desktop> 
       为什么是失败呢?  请自己思考一下, 如果没有结果, 可以参考我之前的博文:http://blog.csdn.net/stpeace/article/details/53046829


       

0 0
原创粉丝点击