xlua貌似不支持单独动态加载cjson.dll,试了各种方式,都是会造成Unity闪退,也不知道原因。
解决办法就是直接编译进xlua.dll
1) 下载lua-cjson源码,并解压到xlua的build文件夹根目录
GitHub - openresty/lua-cjson: Lua CJSON is a fast JSON encoding/parsing module for Lua
2) CMakeLists.txt中加入以下配置
#begin lua-cjson set(CJSON_SRC "lua-cjson-2.1.0.13/strbuf.c" "lua-cjson-2.1.0.13/lua_cjson.c" "lua-cjson-2.1.0.13/fpconv.c" ) #add_definitions(-DUSE_INTERNAL_FPCONV) if (WIN32) add_definitions(-DDISABLE_INVALID_NUMBERS) endif() set_property( SOURCE ${CJSON_SRC} APPEND PROPERTY COMPILE_DEFINITIONS LUA_LIB ) list(APPEND THIRDPART_INC "lua-cjson-2.1.0.13") set(THIRDPART_SRC ${THIRDPART_SRC} ${CJSON_SRC}) #end lua-cjson
3) lua_cjson.c需要做部分修改
a) int luaopen_cjson(lua_State *l)
改为
LUALIB_API luaopen_cjson(lua_State *l)
b) int luaopen_cjson_safe(lua_State *l)
改为
LUALIB_API luaopen_cjson_safe(lua_State *l)
4) 这边要编译Window下的lua5.3的x64版本的dll,所以运行make_win64_lua53.bat
5) 将新生成的xlua.dll替换Unity中的(如果Unity已打开,需要重启下,才能加载新的dll)
6) 测试是否成功
新建MyLua.cs,用于放dll加载代码
namespace XLua.LuaDLL { public partial class Lua { [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaopen_cjson(System.IntPtr L); [MonoPInvokeCallback(typeof(LuaDLL.lua_CSFunction))] public static int LoadCJson(System.IntPtr L) { return luaopen_cjson(L); } } }
新建Lua脚本,Lua/Test8.lua.txt
local cjson = require("cjson") local jsonStr = '{"1": "one"}' local jsonObj = cjson.decode(jsonStr) print(jsonObj["1"])
Test8.cs
public class Test8 : MonoBehaviour { private LuaEnv m_LuaEnv; void Start() { m_LuaEnv = new LuaEnv(); m_LuaEnv.AddLoader((ref string filePath) => { filePath = filePath.Replace('.', '/'); filePath = $"Assets/{filePath}.lua.txt"; var txtAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(filePath); return Encoding.UTF8.GetBytes(txtAsset.text); }); m_LuaEnv.AddBuildin("cjson", XLua.LuaDLL.Lua.LoadCJson); m_LuaEnv.DoString("require('Lua.Test8')"); } void OnDestroy() { if (null != m_LuaEnv) m_LuaEnv.Dispose(); } }
7) 运行结果
参考
[RS] xLua从LuaJit升级Lua5.3记录 - 简书 (jianshu.com)
标签:filePath,cjson,xlua,dll,lua,LuaEnv,Lua From: https://www.cnblogs.com/sailJs/p/18050819