谷歌的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
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
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