先要將proto文件編譯成.pb文件,然后再動態綁定實現lua protobuffer,這就需要了解雲風做的pbc的項目,地址為:https://github.com/cloudwu/pbc/blob/master/binding/lua/README.md
具體的方式是,下載pbc的項目;在pbc/binding/lua下面編譯出protobuf.so放在LUA_PATH下面,或者將protobuf.lua放在
LUA_PATH下,就可以調用protobuf中的庫方法
cd pbc/binding/lua
make
如果提示-fPIC
-->刪去pbc-master/build/o下的所有文件
-->修改pbc-master/Makefile 中的CFLAGS = -O2為CFLAGS = -O2 -fPIC
然后就在pbc-master目錄下make
cd pbc/binding/lua
make
如果提示liblua.a XXX -fPIC
那么唯有重新編譯一次lua了。
-->cd lua-5.1.4/src
-->修改Makefile中的CFLAGS= -O2 -Wall $(MYCFLAGS)為CFLAGS= -O2 -Wall $(MYCFLAGS) -fPIC
-->cd ..
-->make linux
-->sudo make install
cd pbc/binding/lua
make
-->編譯成功
具體的調用方法在pbc的項目中有例子說明,主要的思路是:
1. require "protobuf"
2. 注冊pb文件,利用該文件decode或者encode它的protobuffer對象,見下面的例子:
echo "package test" > test.proto
echo "message Mytest {optional sint64 testid=1;}" >> test.proto
protoc --descriptor_set_out test.pb test.proto
以上方法生成了pb文件,下面的方法是用lua對pb的decode和encode過程
pb = require "protobuf"
protobuf.register_file("./test.pb")
stringbuffer = pb.encode("test.Mytest",
{
testid = 10; })
result = pb.encode("test.Mytest", stringbuffer)
print("result="..result.testid)
這只是雲風提供的方法之一,lua對pb的decode和encode過程的方法之二如下:
file = io.open("./test.pb", "rb")
buffer = file:read "*a"
file:close()
pb.register(buffer)
stringbuffer = pb.encode("test.Mytest",
{
testid =100;
})
result = pb.decode("test.Mytest", stringbuffer)
print("result="..result.testid)
雲風還提供了第三種方法,是用Lua parser,因為這種方法需要用到lua 的 Lpeg模塊,暫時還沒有研究這個功能,等后面再補上。