出处:http://blog.csdn.net/stpeace/article/details/53047276
一起来看看protobuf中容易引起bug的一个细节
test.proto内容为:
- package NS;
- message PointReq
- {
- required int32 x=1;
- required int32 y=2;
- }
- #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>