三.开始一个最简单的项目
好了,一切配置好了,该写代码了,我们做一个最简单的输入输出。新建一个main.cpp,然后把之前生成的person.pb.h和person.pb.cc复制到项目里面,并添加到项目里面。
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
#include <iostream>
#include "person.pb.h"
using namespace std;
using namespace tutorial;
int main()
{
Person person;
person.set_name("flamingo");
person.set_age(18);
cout<<person.name()<<endl;
cout<<person.age()<<endl;
system("pause");
return 0;
}
有些人说可以正常运行,但是我这边不行,主要是
网上查找原因,终于发现,需要在代码里面加两行:
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
#pragma comment(lib,"libprotobuf.lib")
#pragma comment(lib,"libprotoc.lib")
就能正常跑了:
根据语言指导手册创建一个简单的文件:amessage.proto ,内容如下
message AMessage
{
required int32 a=1;
optional int32 b=2;
}
t通过命令行产生相应的.h和.c源文件。 # protoc-c --c_out=.amessage.proto
C文件如下所示
#include<stdio.h>
#include<stdlib.h>
#include"amessage.pb-c.h"
int main (int argc,constchar* argv[])
{
AMessage msg = AMESSAGE__INIT;// AMessage
void*buf; // Buffer to storeserialized data
unsigned len; // Length of serialized data
if(argc !=2&& argc !=3)
{ // Allow one or twointegers
fprintf(stderr,"usage:amessage a [b]\n");
return1;
}
msg.a = atoi(argv[1]);
if(argc ==3){ msg.has_b =1; msg.b = atoi(argv[2]);}
len =amessage__get_packed_size(&msg);
buf = malloc(len);
amessage__pack(&msg,buf);
fprintf(stderr,"Writing %dserialized bytes\n",len);// See the lengthof message
fwrite(buf,len,1,stdout);// Write to stdoutto allow direct command line piping
free(buf);// Free theallocated serialized buffer
return0;
}
注意以下几点:
- 使用A_MESSAGE__INIT宏创建信息的架构
- 参数b是可选的
- amessage__get_packed_size返回数据包的长度。
- a_message__pack 对你设计的信息进行打包。
下面给出对amessage解包的代码。
#include<stdio.h>
#include<stdlib.h>
#include"amessage.pb-c.h"
#define MAX_MSG_SIZE 1024
static size_t
read_buffer (unsigned max_length, uint8_t *out)
{
size_t cur_len =0;
uint8_t c;
while((nread=fread(out+ cur_len,1, max_length - cur_len,stdin))!=0)
{
cur_len += nread;
if(cur_len == max_length)
{
fprintf(stderr,"max messagelength exceeded\n");
exit(1);
}
}
return cur_len;
}
int main (int argc,constchar* argv[])
{
AMessage*msg;
// Read packed message from standard-input.
uint8_t buf[MAX_MSG_SIZE];
size_t msg_len = read_buffer (MAX_MSG_SIZE, buf);
// Unpack the message using protobuf-c.
msg = amessage__unpack(NULL, msg_len, buf);
if(msg == NULL)
{
fprintf(stderr,"errorunpacking incoming message\n");
exit(1);
}
// display the message's fields.
printf("Received: a=%d",msg->a); // required field
if(msg->has_b) // handle optionalfield
printf(" b=%d",msg->b);
printf("\n");
// Free the unpacked message
amessage__free_unpacked(msg, NULL);
return0;
}
编译连接的时候要包含 '-lprotobuf-c',否则编译不通过
Test by piping one program into the next atcommand line:
#./amessage_serialize 10 2 | ./amessage_deserialize ---->使用管道命令
Writing:4 serialized bytes
Received: a=10 b=2