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

出处:http://blog.csdn.net/stpeace/article/details/53047276

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

我们来看看如下代码的一个小bug:

        test.proto内容为:

  1. package NS;    
  2. message PointReq   
  3. {    
  4.     required int32 x=1;    
  5.     required int32 y=2;    
  6. }  
       main.cpp为:
  1. #include <iostream>  
  2. #include <string>  
  3. using namespace std;  
  4.   
  5. #include "test.pb.h"  
  6. using namespace NS;  
  7.   
  8. int main()  
  9. {  
  10.     PointReq point;  
  11.     point.set_x(1);  
  12.     point.set_y(0);  
  13.   
  14.     string tmp;  
  15.     bool ret = point.SerializeToString(&tmp); // 这里要传地址  
  16.     if (ret)  
  17.     {  
  18.         printf("encode ok!\n");  
  19.     }  
  20.     else  
  21.     {  
  22.         printf("encode error!\n");  
  23.         return -1;  
  24.     }  
  25.   
  26.     // 为了便于网络传输, 这里需要转化成指针式buffer  
  27.     const char *p = tmp.c_str();  
  28.       
  29.     string s = p;  
  30.       
  31.     PointReq point2;  
  32.     ret = point2.ParseFromString(s);  
  33.     if (ret)  
  34.     {  
  35.         printf("decode ok, %d, %d\n", point2.x(), point2.y());  
  36.     }  
  37.     else  
  38.     {  
  39.         printf("decode error!\n");  
  40.         return -2;  
  41.     }  
  42.       
  43.     return 0;  
  44. }  

        结果为:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值