在https://code.google.com/p/protoc-gen-lua/ 下載網易兄弟寫的lua的protobuf插件(網易都把pb給弄完了,as3的也是他們寫的..)
編譯python版的protobuf模塊
在https://code.google.com/p/protobuf/downloads/list 下載官方的原生版本protobuf, 這里發文時使用的是2.4.1版本
編譯出protoc執行文件, 放一份在protobuf-2.4.1\src\下
下載python2.7版本, 在protobuf-2.4.1\python下運行python setup.py install(如果找不到python請給python絕對路徑)
這一步, python會下一個蛋( 真的是一個python的egg文件 ), 然后編譯出python版本的protobuf模塊放置在python下
制作protoc-gen-lua的批處理
放一份protoc在protoc-gen-lua的plugin目錄
編寫批處理:protoc-gen-lua.bat
@python "%~dp0protoc-gen-lua"
協議目錄生成腳本
在你需要放置協議的目錄編寫如下批處理
buildproto.bat
rd /S /Q .\%1%
"..\..\src\protoc-gen-lua\plugin\protoc.exe" --plugin=protoc-gen-lua="..\..\src\protoc-gen-lua\plugin\protoc-gen-lua.bat" --lua_out=. %1%.proto
注意protoc.exe及protoc-gen-lua.bat的路徑符合你的路徑
再編寫要編譯的proto協議的批處理generate.bat
call buildproto.bat loginsvc
執行generate.bat后, 將會編譯同目錄下的loginsvc.proto,輸出loginsvc_pb.lua
編譯鏈接lua的pb庫
將protoc-gen-lua\protobuf\目錄拷貝到之前的協議目錄
將其下的pb.c鏈入你的工程, 注意VS2010的VC下需要修改源碼
1.將 #include <endian.h>修改為
#ifndef _WIN32
#include <endian.h>
#endif
避免在windows下缺失文件報錯.
2. 調整struct_unpack函數前幾行為
static int struct_unpack(lua_State *L)
{
uint8_t format = luaL_checkinteger(L, 1);
size_t len;
const uint8_t* buffer = (uint8_t*)luaL_checklstring(L, 2, &len);
size_t pos = luaL_checkinteger(L, 3);
uint8_t out[8];
buffer += pos;
避免VS2010的VC編譯器過于標準, 嚴格要求C風格函數變量前置聲明
在lua_State聲明后添加如下代碼
extern "C" { int luaopen_pb (lua_State *L);} // 注意防在命名空間外的全局聲明
luaopen_pb( L ); // 直接注入全局pb, 避免動態加載pb.dll造成的一系列跨平臺問題
lua中使用pb
local loginsvc_pb = require “loginsvc_pb”
local REQ = loginsvc_pb.CheckVersionREQ()
local Data = REQ:SerializeToString( )
local ACK = loginsvc_pb.CheckVersionACK()
ACK:ParseFromString( Data )
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
我的工程目錄
script\
protobuf\
buildproto.bat
generate.bat
loginsvc_pb.lua
loginsvc.proto
Main.lua
src\
protoc-gen-lua\
example\
plugin\
protobuf\