轉自: http://www.voidcn.com/article/p-vmuovdgn-bam.html
(1)lua實現protobuf的簡介
但遺憾的是,官網的probocol buffers並不支持lua,雲風大俠做的pbc的項目,地址為:https://github.com/cloudwu/pbc/blob/master/binding/lua/README.md. 實現了protobuf對lua的支持。
主要步驟如下:
第一步: You specify how you want the information you're serializing to be structured by defining protocol buffer message types in .proto
files(定義.proto)
第二步: Once you've defined your messages, you run the protocol buffer compiler for your application's language on your .proto
file to generate data access classes.(編譯.proto文件,生成.pb文件)
第三步: 使用pbc庫提供的函數,實現protobuf.
(2)安裝protobuf
下載地址:https://code.google.com/p/protobuf/
安裝protobuf后,protobuf提供了protoc指令,可以編譯.proto文件
#protobuf
cd $WORKDIR
tar xfz protobuf-2.4.1.tar.gz
cd protobuf-2.4.1
./configure || exit $?
make -j3 || exit $?
make install || exit $?
使用方法:protoc --descriptor_set_out test.pb test.proto
使用protoc -h 可以查看protoc的其他選項
把 多個proto 文件編譯到一個.pb文件的方法: protoc --descriptor_set_out=$confdir/common.cmd.pb $protodir/*.proto
(3) 安裝pbc
rm -rf pbc-master
tar xfz pbc-master.tar.gz
cd pbc-master
make || exit $? cd binding/lua/ && make || exit $? cp -rf protobuf.so $WORKDIR/lualib/
把編譯生成的protobu.so文件放到LUA_PATH目錄里面,當require "protobuf"的時候,可以找到這個文件。放在哪里不重要,重要的是讓lua找到它。
除此之外,還有一步非常重要:
把 pbc/binding/lua/protobuf.lua 賦值到LUA_PATH目錄中,當require "protobuf"的時候,可以找到這個文件。
http://www.cnblogs.com/ghost240/p/3253092.html 這篇文章中說,
LUA_PATH下,就可以調用protobuf中的庫方法 是錯的!在pbc/binding/lua下面編譯出protobuf.so放在LUA_PATH下面,或者將protobuf.lua放在
(4)如何使用pbc
a: 定義一個common.proto文件
package Common;
message accountRegister { optional string accountid = 1; optional string hashedpwd = 2; }
b:編碼common.proto,生成common.pb文件
protoc --descriptor_set_out=/common.pb common.proto
c: 初始化protobuf
require("protobuf") 特別需要注意
-- 生成的pb文件
local pbfile ="/path/to/common.pb" local pbdesc = io.open(pbfile, "rb") if not pbdesc then echoError("failed to load protobuf description file:" .. pbfile) return end local pbbuffer = pbdesc:read("*a") protobuf.register(pbbuffer) pbdesc:close()
d: 編碼 protobuf.encode(ptype, msg)
ptype = 'Common.accountRegister' 千萬不要忘了 Common前綴
msg = {accountid = '123', hashedpwd = '123456'} msg的聲明的格式必須要和proto文件里聲明的一樣,否則編碼不通過
e: 解碼 protobuf.decode(pbtype, msgbuf) 返回msg 和err,具體的返回內容請參考pbc的文件