protobuf-c應用樣例

源碼

源碼地址: https://github.com/protobuf-c/protobuf-c.git

編譯

./autogen.sh && ./configure && make && make install

應用

根據協議格式生成源碼與頭文件

amessage.proto 文件內容如下:

message AMessage {
required int32 a=1;
optional int32 b=2;
}

根據amessage.proto 生成C語言頭文件與源碼
protoc-c --c_out=. amessage.proto

生成如下文件:

amessage.pb-c.c
amessage.pb-c.h

使用樣例:

封裝協議:pack.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;
}

解包協議:unpack.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 pack.c amessage.pb-c.c -lprotobuf-c
gcc -o deserialize unpack.c amessage.pb-c.c -lprotobuf-c

執行結果

./serialize 10 2 | ./deserialize
Writing 4 serialized bytes
Received: a=10  b=2

參考

【github樣例】https://github.com/protobuf-c/protobuf-c/wiki/Examples
【Protocol Buffer 新手指南 】http://blog.huzhifeng.com/2016/03/20/Protocol-Buffer-Beginner-Guide/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章