protocol buffers c语言的使用

7 篇文章 0 订阅
5 篇文章 0 订阅

以下源码示例来源于https://github.com/protobuf-c/protobuf-c/wiki/Examples

定义消息
message AMessage {
  required int32 a=1; 
  optional int32 b=2;
}
安装protobuf-c

我们需要把proto文件编译成c源码,才能在代码中使用,所以需要用到官方的编译工具

sudo apt-get install protobuf-c-compiler
编译
protoc-c --c_out=. amessage.proto 
//将会产生amessage.pb-c.c  amessage.pb-c.h两个文件
代码中使用

序列化:

//serialize_main.c
#include <stdio.h>
#include <stdlib.h>
#include "amessage.pb-c.h"

int main (int argc, const char * argv[]) 
{
  AMessage msg = AMESSAGE__INIT; // AMessage
  void *buf;                     // Buffer to store serialized data
  unsigned len;                  // Length of serialized data

  if (argc != 2 && argc != 3)
  {   // Allow one or two integers
    fprintf(stderr,"usage: amessage a [b]\n");
    return 1;
  }

  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 %d serialized bytes\n",len); // See the length of message
  fwrite(buf,len,1,stdout); // Write to stdout to allow direct command line piping

  free(buf); // Free the allocated serialized buffer
  return 0;
}

反序列化:

//unserialize_main.c
#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;
  size_t nread;
  while ((nread=fread(out + cur_len, 1, max_length - cur_len, stdin)) != 0)
  {
    cur_len += nread;
    if (cur_len == max_length)
    {
      fprintf(stderr, "max message length exceeded\n");
      exit(1);
    }
  }
  return cur_len;
}


int main (int argc, const char * 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, "error unpacking incoming message\n");
    exit(1);
  }

  // display the message's fields.
  printf("Received: a=%d",msg->a);  // required field
  if (msg->has_b)                   // handle optional field
    printf("  b=%d",msg->b);
  printf("\n");

  // Free the unpacked message
  amessage__free_unpacked(msg, NULL);
  return 0;
}
编译可执行程序
gcc -o serialize_main serialize_main.c amessage.pb-c.c -lprotobuf-c
gcc -o unserialize_main unserialize_main.c amessage.pb-c.c -lprotobuf-c
运行
./serialize_main 10086 -123 | ./unserialize_main
使用protobuf C语言,需要进行以下步骤: 1. 下载protobuf库并安装 2. 编写.proto文件,定义数据结构 3. 生成对应的C语言代码 4. 编写C程序,使用protobuf库解析和序列化数据 以下是一个简单的例子: 假设有一个.proto文件定义了一个Person数据结构: ``` syntax = "proto3"; message Person { string name = 1; int32 age = 2; } ``` 1. 下载protobuf库并安装 可以从protobuf官网 https://developers.google.com/protocol-buffers/docs/cpptutorial 下载protobuf库的源代码,然后根据官方文档进行编译和安装。 2. 生成对应的C语言代码 在终端中输入以下命令: ``` protoc --proto_path=./ --cpp_out=./ person.proto ``` 其中,--proto_path参数指定.proto文件所在的目录,--cpp_out参数指定生成C++代码的输出目录。执行完该命令后,会生成person.pb.h和person.pb.cc两个文件,其中person.pb.h包含了Person数据结构的定义和相关函数的声明,person.pb.cc包含了相关函数的实现。 3. 编写C程序,使用protobuf库解析和序列化数据 ```c #include <iostream> #include <fstream> #include "person.pb.h" using namespace std; int main() { // 创建一个Person对象 Person person; person.set_name("Alice"); person.set_age(20); // 将Person对象序列化为二进制数据 string data; person.SerializeToString(&data); // 将二进制数据反序列化为Person对象 Person new_person; new_person.ParseFromString(data); // 输出新生成的Person对象的name和age属性 cout << "Name: " << new_person.name() << endl; cout << "Age: " << new_person.age() << endl; return 0; } ``` 以上代码将输出: ``` Name: Alice Age: 20 ``` 这里使用protobuf库提供的两个函数:SerializeToString和ParseFromString。SerializeToString函数将Person对象序列化为一个二进制字符串,ParseFromString函数将该二进制字符串反序列化为一个新的Person对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值