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

972 篇文章 329 订阅
309 篇文章 11 订阅

        我们已经介绍过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;
    }

	// 为了便于网络传输, 这里需要转化成指针式buffer
	const 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 clean
rm -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 done
g++: -lprotobuf: linker input file unused because linking not done
g++    -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


       

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值