Protobuf c的使用范例

protobuffer (简称PB) 网上的文章一大堆,随便看看,PB使用起来非常方便。这里主要讲讲Protobuf C(简称PC)的使用

1,代码

https://github.com/protobuf-c/protobufc/releases/download/v1.3.2/protobuf-c-1.3.2.tar.gz

2,编译

先决条件(PB也要安装)

sudo apt-get install autoconf automake libtool curl make g++ unzip

PC的编译

./autogen.sh && make &&make check之后sudo make install;sudo ldconfig

3,“编译”proto文件

protoc-c -I=./proto --c_out=./proto ./proto/main.proto

4,proto文件定义

这部分和PB是完全一样的,这里就不重复了

enum MessageType {
    MSG_REQUEST = 0;
    MSG_NOTIFICATION = 1;
}

message Message {
    MessageType type = 1;
    fixed32 seq = 2;
    fixed64 session_id = 3;
    string using_for_test = 4;
    Response response = 5;
}

message Response {
    enum ResponseType {
        RESPONSE_SYSTEM_STATE = 0;
        RESPONSE_HARDWARE_STATE = 1;

    }
    ResponseType response_type = 1;
}

5,代码中对PC定义的数据的访问方式

生成一个消息

    /* example of using protobuf message */

    Message msg = MESSAGE__INIT;
    Response res = RESPONSE__INIT;

    //response msg
    msg.response = &res;
    res.response_type = RESPONSE_HARDWARE_STATE;

    msg->using_for_test = (char *)malloc(PROTO_STRING_LEN);
    memset(msg->using_for_test, 0, PROTO_STRING_LEN);

序列化一个消息

    //pack
    int len = message__get_packed_size(&msg);
    uint8_t *buf = (uint8_t *)malloc(len);
    message__pack(&msg, buf);

反序列化一个消息

    Message*rev = message__unpack(NULL, len, buf);
    message__free_unpacked(rev, NULL);

不要忘了手动释放申请的资源 (这点PC很麻烦,涉及到动态长度的元素,资源要手动申请释放)

  free(buf);
  free(msg->using_for_test);

 

posted @ 2019-10-24 15:39  Ray.floyd  阅读(4915)  评论(0编辑  收藏  举报