zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    [设计模式]之依赖倒置
    CSS的三种使用方式
    CSS的语法结构
    学习 jQueryMobile 第一个程序
    初识 GoogleMap
    程序员考试
    程序员考试
    CSS学习
    认识CSS
    开始忙一段时间
  • 原文地址:https://www.cnblogs.com/rayfloyd/p/11732582.html
Copyright © 2011-2022 走看看