protobuf-c 版本安裝和測試
阿新 • • 發佈:2020-12-02
1. 準備與安裝
軟體包:protobuf-2.6.1.zip, protobuf-c-master.zip
apt-get install pkg-config unzip protobuf-2.6.1.zip ./configure --prefix=/usr/ make make install unzip protobuf-c-master.zip ./configure --prefix=/usr/ make make install
2. 安裝驗證
cd protobuf-c-master/t
protoc-c --c_out=./ test.proto //無報錯則說明安裝成功
3. 測試demo
3.1 編寫proto檔案
vim UserInfo.proto
enum UserStatus { UNKNOWN = 0; IDLE = 1; BUSY = 2; } message UserInfo { required string name = 1; required uint32 age = 2; optional string phone = 3; required UserStatus stat = 4; optional string email = 5; }
3.2 使用命令protoc-c 將proto檔案進行匯出.c和.h檔案
protoc-c --c_out=./ UserInfo.proto
3.3 編寫main.c
#include "UserInfo.pb-c.h" #include <stdio.h> int main() { uint8_t buffer[1024] = {0}; UserInfo user; user_info__init(&user); user.name = "dabai"; user.age = 18; user.stat = USER_STATUS__IDLE; size_t length = user_info__pack(&user, buffer); UserInfo *userInfo = user_info__unpack(NULL, length, buffer); if(!userInfo){ printf("user_information__unpack is fail!!!\n"); return -1; } printf("Unpack: %s %d %d\n", userInfo->name, userInfo->age, userInfo->stat); user_info__free_unpacked(userInfo, NULL); return 0; }
3.4 編譯與執行
gcc main.c UserInfo.pb-c.c -I ./ -lprotobuf-c -o main ./main Unpack: dabai 18 1