protobuf與c語言

谷歌的protobuf支持很多種語言,唯獨不支持c,而在嵌入式設備上大都是c語言開發,有很大的需求,

由此出現了很多非官方的支持c語言版ptotobuf。一直在更新的好像就nanopb和protobuf-c。

比如

 

nanopb的實現。

1)安裝google protobuf,以C++/unix平臺爲基礎,安裝一些必要工具。

官方教程,注意下載all版本;

參考:
https://github.com/protocolbuffers/protobuf/blob/master/src/README.md

到能正確輸出protoc --version

protoc --version

有時不能輸出是因爲路徑或庫沒有更新
protoc: error while loading shared libraries: libprotoc.so.22: cannot open shared object file: No such file or directory
sudo ldconfig
或者
export LD_LIBRARY_PATH=/usr/local/lib

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

2)安裝python相關支持,注意版本。

參考:

https://github.com/protocolbuffers/protobuf/tree/master/python

遇到


protobuf-3.11.2# 
cd python/
python setup.py build

Traceback (most recent call last):
  File "setup.py", line 4, in <module>
    from distutils import util
ImportError: cannot import name 'util'

缺少模塊錯誤:
缺少模塊'distutils.util'
參考: https://www.cnblogs.com/phpper/p/10887602.html

python2/3 共存,安裝pip
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

3)下載最新版nanopb:

https://jpa.kapsi.fi/nanopb/download/

具體操作流程,參考:

https://github.com/nanopb/nanopb

3.1)其中指出瞭如何安裝google protobuf:

3.2)以及如何編譯proto文件:

編譯的一些條件

分2步編譯:

一步編譯:

 

3.3)在項目工程中應用:

4) any 類型的處理:

參考:https://github.com/nanopb/nanopb/issues/163

理解any的type_url及buffer定義負載。

依然是定義好options中的max_size

對應repeat類型定義好max_count,

除了參考example外,test下的alltypes類型的encode/decode也是很好的參考。

 

 

遇到的問題:

明明文件在顯示elf32,執行make腳本時顯示找不到文件(單獨執行可以).

原因在於64位平臺上執行32位的應用需要相關鏈接庫。

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386

refs:

https://askubuntu.com/questions/133389/no-such-file-or-directory-but-the-file-exists

 

其他:

編譯proto文件中有時需要對string類型限制最大長度,

如果分成2個文件,一個proto,一個options,options中需要保護package的域名如

proto中  package爲a.b.c ,message 爲d,

則options中爲 a.b.c.d.stringproperty max_size:128

 

參考:

https://stackoverflow.com/questions/57367265/how-to-compile-nanopb-proto-file-into-h-and-c-files-using-nanopb-and-protobuf

http://socialledge.com/sjsu/index.php/S15:_Tree_Node_using_Google_Protocol_Buffers#NanoPB

 

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