protobuf-IOS简单总结(编译、环境搭建)

来源:互联网 发布:慢镜头拍摄软件 编辑:程序博客网 时间:2024/04/29 14:20

什么是protobuf?


Protocol Buffers are a way of encoding structured data in an efficient yet extensible format. Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats.


一、安装流程

(1)进入终端 跳转至protobuf文件夹. cd xxxxxxxxxxxxxx(路径)
(2)切换用户身份. sudo su 
(3)执行 ./configure
(4)执行 make
(5)执行 make check(可能message.cc会报错,解决办法请看下面)
(6)执行 make install
(7)检查是否安装成功,执行 protoc —version


二、安装protobuf编译器时遇到的问题 

(1)message.cc 报错,原因是因为少引了一个库 (据说可能是因为clang跟GCC不同的原因)

解决办法:在message.cc中 加入 #include <iostream>
(2)可能会缺少<tr1/tuple>  其原因貌似是因为XCODE5 编译器为  Apple LLVM version 5.0 (clang-500.2.76) (based on LLVM 3.3svn) 
解决办法:不知道是不是因为那个压缩包的原因(PS:别人给的),我重新从官网下了个2.4.1就正常了

环境:XCODE5.0 
    protobuf 2.4.1 
    MAC OS 10.9.1


三、protobuf.a静态库的制作,跟平时的一样

(1)新建一个静态库工程
(2)删除原生成.h和.m文件
(3)导入protobuf文件夹中的src/google的文件夹
(4)删除xcode中google/compiler文件夹
(5)删除xcode中google下所有的unittest文件(包括子文件夹),包括test_util和test_util_lite(PS:挺多的)
(6)在项目配置 Header Search Paths中引入相关路径xxxx/src等,(XCODE5中 compiler for C/C++/Objective-C 默认是Apple LLVM 5.0,clang的,不过一样可以用,在终端中可以查看版本号, 命令:  clang -v)
(7)到Build Phases中copy ties下注入src/google相关头文件



四、protobuf生成C++文件

终端中输入以下命令生成C++文件
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
$SRC_DIR:文件所在路径
$DST_DIR:输出路径
例如:protoc -I=/Users/dale_hui/Pictures/ --cpp_out=/Users/dale_hui/Pictures/    /Users/dale_hui/Pictures/wechat.proto 
PS:protobuf2.5生成出来的c++文件,在2.4.1不通用 生成出来的文件分别为.h和.cc


五、简单的定义

message SendUp {required bytes voice = 1;optional int32 result_per_page = 3 [default = 10]; repeated int32 samples = 4 [packed=true]; }



格式为:限定修饰符 数据类型 字段名 =字段数字别名 [字段默认值]

[packed=true]可以保证更高效的编码

限定修饰符的说明(来自官网)
required: a well-formed message must have exactly one of this field.
optional: a well-formed message can have zero or one of this field (but not more than one).
repeated: this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved. 

至于message SendUp{}有些像声明结构体一样,当然它可以嵌套在message中,编译成C++后,使用时,就跟普通的类使用没有区别.

枚举值的使用(此处跟C++有区别,用的是 ’;’ 号隔开,而不是 ‘,')
enum Foo {  VALUE_A = 1;  VALUE_B = 5;  VALUE_C = 1234;} 

肉眼目测protobuf 字符串的结构大概为: \n  字符串长度  数据内容  长度大概是(2字节+2字节+N字节)


注释:protobuf中则可以使用双斜杠风格 ‘ // ‘
导入定义: import "myproject/other_protos.proto”; 


但愿以上总结能避免你们少跳坑

更多的使用可参考Google文档:https://developers.google.com/protocol-buffers/docs/proto?hl=en



protobuf下载地址  https://code.google.com/p/protobuf/downloads/list 
Google快速使用小例子 https://code.google.com/p/protobuf/








0 0
原创粉丝点击