ToLua tolua_runtime添加第三方库lua_protobuf(protobuf3)

需要准备:

  1. tolua_runtime源码 下载

  2. lua_protobuf 下载

  3. 配置好的环境msys2 链接 提取码:6666


一、将lua-protobuf的pb.h和pb.c替换tolua_runtime根目录的pb.c

二、打开pb.c替换luaop_pb函数

LUALIB_API int luaopen_pb(lua_State *L) {
        luaL_Reg libs[] = {
            { "pack",     Lbuf_pack     },
            { "unpack",   Lslice_unpack },
    #define ENTRY(name) { #name, Lpb_##name }            ENTRY(clear),
            ENTRY(load),
            ENTRY(loadfile),
            ENTRY(encode),
            ENTRY(decode),
            ENTRY(types),
            ENTRY(fields),
            ENTRY(type),
            ENTRY(field),
            ENTRY(typefmt),
            ENTRY(enum),
            ENTRY(defaults),
            ENTRY(hook),
            ENTRY(tohex),
            ENTRY(result),
            ENTRY(option),
            ENTRY(state),
    #undef  ENTRY            { NULL, NULL }
        };
        luaL_Reg meta[] = {
            { "__gc", Lpb_delete },
            { "setdefault", Lpb_state },
            { NULL, NULL }
        };
        if (luaL_newmetatable(L, PB_STATE)) {
            luaL_setfuncs(L, meta, 0);
            lua_pushvalue(L, -1);
            lua_setfield(L, -2, "__index");
        }
        #if LUA_VERSION_NUM < 502        luaL_register(L, "pb", libs);
        #else        luaL_newlib(L, libs);
        #endif
        return 1;
    }


三、编译

  1. 打开msys2 32编译环境 cd到tolua_runtime位置

  2. ./build_win32.sh 编译win的tolua.dll,目录在Plugins/x86下

  3. 打开编辑android相关的(build_arm.sh、build_x86.sh、link_arm64.bat),把NDK路径改为本电脑路径,我用的版本是android-ndk-r10e-windows-x86_64,然后在msys2 的32位下执行 ./build_arm.sh,执行./build_x86.sh。编译后的tolua.so在Plugins/Android下

  4. arm64的参考上面步骤,使用msys2 64编译环境

  5. ios和mac没试,需要MAC系统,没条件的可以搞虚拟机弄弄,用终端直接执行相关脚本。


四、库的使用

1.在Unity中找到LuaDLL.cs,找到lua_open_pb位置,替换代码

/*
** third party library
*/
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaopen_pb(IntPtr L);

[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaopen_pb_io(IntPtr L);

[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaopen_pb_conv(IntPtr L);

[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaopen_pb_buffer(IntPtr L);

[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaopen_pb_slice(IntPtr L);


2.在你创建虚拟机的地方添加打开Lib

// m_LuaState 为 LuaState 对象
m_LuaState.OpenLibs(LuaDLL.luaopen_pb_io);
m_LuaState.OpenLibs(LuaDLL.luaopen_pb_conv);
m_LuaState.OpenLibs(LuaDLL.luaopen_pb_buffer);
m_LuaState.OpenLibs(LuaDLL.luaopen_pb_slice);


3.复制lua-protobuf的protoc.lua和serpent.lua到你的lua脚本目录


首页 我的博客
粤ICP备17103704号