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);