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