Xlua分析:C#调用Lua

本篇主题是C#如何调用lua的补充。

xLua交互知识

参考官方文档《programming in lua》的第24章开头,里面很详细地阐述了Lua和C++是如何实现交互的:栈操作。Lua API用一个抽象的栈在Lua与C之间交换值。栈中的每一条记录都可以保存任何 Lua 值。如果想要从Lua请求一个值(比如一个全局变量的值)则调用Lua,被请求的值将会被压入栈;如果想要传递一个值给 Lua,首先将这个值压入栈,然后调用 Lua(这个值就会被弹 出)。几乎所有的 API函数都用到了栈。而C#显而易见也可以和C++一侧进行交互,由此即可得出lua和C#可以通过C/C++这一层来进行通信,主要方法即是lua的堆栈操作。

C#获取Lua入口

首先写一段测试代码:

[LuaCallCSharp]
public class LuaTableTest
{
    public LuaTable tab = null;
    public Action<LuaTable> luaFunc = null;
}

然后经过Xlua Generate Code后可以观察Set方法,得到流程的起点:translator.GetObject

[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_tab(RealStatePtr L)
{
	try {
        ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
			
        XluaTool.LuaTableTest gen_to_be_invoked = (XluaTool.LuaTableTest)translator.FastGetCSObj(L, 1);
        gen_to_be_invoked.tab = (XLua.LuaTable)translator.GetObject(L, 2, typeof(XLua.LuaTable));
            
    } catch(System.Exception gen_e) {
        return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
    }
    return 0;
}
        
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_luaFunc(RealStatePtr L)
{
	try {
        ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
			
        XluaTool.LuaTableTest gen_to_be_invoked = (XluaTool.LuaTableTest)translator.FastGetCSObj(L, 1);
        gen_to_be_invoked.luaFunc = translator.GetDelegate<System.Action<XLua.LuaTable>>(L, 2);
            
    } catch(System.Exception gen_e) {
        return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
    }
    return 0;
}

可以看到,translator.GetObject负责把相应Lua类型转换成C#类型数据并返回。而GetObject内部是由GetCaster函数实现转换的:

public ObjectCast GetCaster(Type type)
{
    if (type.IsByRef) type = type.GetElementType();

    Type underlyingType = Nullable.GetUnderlyingType(type);
    if (underlyingType != null)
    {
        return genNullableCaster(GetCaster(underlyingType)); 
    }
    ObjectCast oc;
    if (!castersMap.TryGetValue(type, out oc))
    {
        oc = genCaster(type);
        castersMap.Add(type, oc);
    }
    return oc;
}

castersMap内部已经定义了各个类型的转换函数:

public ObjectCasters(ObjectTranslator translator)
{
    this.translator = translator;
    castersMap[typeof(char)] = charCaster;
    castersMap[typeof(sbyte)] = sbyteCaster;
    castersMap[typeof(byte)] = byteCaster;
    castersMap[typeof(short)] = shortCaster;
    castersMap[typeof(ushort)] = ushortCaster;
    castersMap[typeof(int)] = intCaster;
    castersMap[typeof(uint)] = uintCaster;
    castersMap[typeof(long)] = longCaster;
    castersMap[typeof(ulong)] = ulongCaster;
    castersMap[typeof(double)] = getDouble;
    castersMap[typeof(float)] = floatCaster;
    castersMap[typeof(decimal)] = decimalCaster;
    castersMap[typeof(bool)] = getBoolean;
    castersMap[typeof(string)] =  getString;
    castersMap[typeof(object)] = getObject;
    castersMap[typeof(byte[])] = getBytes;
    castersMap[typeof(IntPtr)] = getIntptr;
    //special type
    castersMap[typeof(LuaTable)] = getLuaTable;
    castersMap[typeof(LuaFunction)] = getLuaFunction;
}

所以接下来的任务无非就是研究getLuaTable和getLuaFunction如何实现的了。

C#获取Lua table

getLuaFunction实现如下:

private object getLuaTable(RealStatePtr L, int idx, object target)
{
    if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA)
    {
        object obj = translator.SafeGetCSObj(L, idx);
        return (obj != null && obj is LuaTable) ? obj : null;
    }
    if (!LuaAPI.lua_istable(L, idx))
    {
        return null;
    }
    LuaAPI.lua_pushvalue(L, idx);
    return new LuaTable(LuaAPI.luaL_ref(L), translator.luaEnv);
}

主要步骤即是通过luaL_ref添加到Lua注册表中并获取索引位置,创建一个C#侧的LuaTable对象用于管理。之后获取这个table即可直接用这个LuaTable对象即可。

如果使用测试代码

LuaTableTest.tab.Get<int>("testVal")

来获取相应变量信息,实际上内部执行的是table.Get接口:

public void Get<TKey, TValue>(TKey key, out TValue value)
{
#if THREAD_SAFE || HOTFIX_ENABLE
    lock (luaEnv.luaEnvLock)
    {
#endif
        var L = luaEnv.L;
        var translator = luaEnv.translator;
        int oldTop = LuaAPI.lua_gettop(L);
        LuaAPI.lua_getref(L, luaReference);
        translator.PushByType(L, key);

        if (0 != LuaAPI.xlua_pgettable(L, -2))
        {
            string err = LuaAPI.lua_tostring(L, -1);
            LuaAPI.lua_settop(L, oldTop);
            throw new Exception("get field [" + key + "] error:" + err);
        }

        LuaTypes lua_type = LuaAPI.lua_type(L, -1);
        Type type_of_value = typeof(TValue);
        if (lua_type == LuaTypes.LUA_TNIL && type_of_value.IsValueType())
        {
            throw new InvalidCastException("can not assign nil to " + type_of_value.GetFriendlyName());
        }

        try
        {
            translator.Get(L, -1, out value);
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            LuaAPI.lua_settop(L, oldTop);
        }
#if THREAD_SAFE || HOTFIX_ENABLE
    }
#endif
}

可以看到,我们首先通过getref(之前new luaTable的时候已经做了添加ref的操作了)拿到table的reference,然后再通过这个reference查询到key的位置并取出,即可得到相应的数据了。

根据LuaTable获取变量

 在Get代码中有一处细节:translator.Get,内部有提前封装好的基本类型对象转换,比如int、double、string类型等,这些都可以直接通过Lua API实现转换,LuaAPI.xlua_tointeger这些也仅仅是对原生API的简单封装。

public void Get<T>(RealStatePtr L, int index, out T v)
{
    Func<RealStatePtr, int, T> get_func;
    if (tryGetGetFuncByType(typeof(T), out get_func))
    {
        v = get_func(L, index);
    }
    else
    {
        v = (T)GetObject(L, index, typeof(T));
    }
}
bool tryGetGetFuncByType<T>(Type type, out T func) where T : class
{
    if (get_func_with_type == null)
    {
        get_func_with_type = new Dictionary<Type, Delegate>()
        {
            {typeof(int), new Func<RealStatePtr, int, int>(LuaAPI.xlua_tointeger) },
            {typeof(double), new Func<RealStatePtr, int, double>(LuaAPI.lua_tonumber) },
            {typeof(string), new Func<RealStatePtr, int, string>(LuaAPI.lua_tostring) },
            {typeof(byte[]), new Func<RealStatePtr, int, byte[]>(LuaAPI.lua_tobytes) },
            {typeof(bool), new Func<RealStatePtr, int, bool>(LuaAPI.lua_toboolean) },
            {typeof(long), new Func<RealStatePtr, int, long>(LuaAPI.lua_toint64) },
            {typeof(ulong), new Func<RealStatePtr, int, ulong>(LuaAPI.lua_touint64) },
            {typeof(IntPtr), new Func<RealStatePtr, int, IntPtr>(LuaAPI.lua_touserdata) },
            {typeof(decimal), new Func<RealStatePtr, int, decimal>((L, idx) => {
                decimal ret;
                Get(L, idx, out ret);
                return ret;
            }) },
            {typeof(byte), new Func<RealStatePtr, int, byte>((L, idx) => (byte)LuaAPI.xlua_tointeger(L, idx) ) },
            {typeof(sbyte), new Func<RealStatePtr, int, sbyte>((L, idx) => (sbyte)LuaAPI.xlua_tointeger(L, idx) ) },
            {typeof(char), new Func<RealStatePtr, int, char>((L, idx) => (char)LuaAPI.xlua_tointeger(L, idx) ) },
            {typeof(short), new Func<RealStatePtr, int, short>((L, idx) => (short)LuaAPI.xlua_tointeger(L, idx) ) },
            {typeof(ushort), new Func<RealStatePtr, int, ushort>((L, idx) => (ushort)LuaAPI.xlua_tointeger(L, idx) ) },
            {typeof(uint), new Func<RealStatePtr, int, uint>(LuaAPI.xlua_touint) },
            {typeof(float), new Func<RealStatePtr, int, float>((L, idx) => (float)LuaAPI.lua_tonumber(L, idx) ) },
        };
    }

    Delegate obj;
    if (get_func_with_type.TryGetValue(type, out obj))
    {
        func = obj as T;
        return true;
    }
    else
    {
        func = null;
        return false;
    }
}

C#获取Function

以上已经说明,如果只是为了获取某个table内部的相关变量,其实走Get就已经满足需求,但是有些函数依然还需要调用,比如一些匿名函数:

XluaTool.LuaTableTest.luaFunc= function()
end

此时需要转换成delegate形式供C#侧调用,如第二段代码块中所示:

gen_to_be_invoked.luaFunc = translator.GetDelegate<System.Action<XLua.LuaTable>>(L, 2);

而跳转GetDelegate直到CreateDelegateBridge函数,会发现其中有一些代码和GetLuaTable非常相似,即会存储在lua注册表中,然后给出一个索引,最后通过DelegateBridgeBase类进行存储:

public object CreateDelegateBridge(RealStatePtr L, Type delegateType, int idx)
{
    ......
    LuaAPI.lua_pushvalue(L, idx);
    int reference = LuaAPI.luaL_ref(L);
    LuaAPI.lua_pushvalue(L, idx);
    LuaAPI.lua_pushnumber(L, reference);
    LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX);
    DelegateBridgeBase bridge;
    try
    {
#if (UNITY_EDITOR || XLUA_GENERAL) && !NET_STANDARD_2_0
        if (!DelegateBridge.Gen_Flag)
        {
            bridge = Activator.CreateInstance(delegate_birdge_type, new object[] { reference, luaEnv }) as DelegateBridgeBase;
        }
        else
#endif
        {
            bridge = new DelegateBridge(reference, luaEnv);
        }
    }
    ......
}

LuaBase Dispose

C#这边释放lua侧资源时需要调用相关接口,以防Lua侧一直认为C#侧持有lua相关资源。可以着重观察Xlua给的LuaBase析构函数的处理方式:

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

public virtual void Dispose(bool disposeManagedResources)
{
    if (!disposed)
    {
        if (luaReference != 0)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
                bool is_delegate = this is DelegateBridgeBase;
                if (disposeManagedResources)
                {
                    luaEnv.translator.ReleaseLuaBase(luaEnv.L, luaReference, is_delegate);
                }
                else //will dispse by LuaEnv.GC
                {
                    luaEnv.equeueGCAction(new LuaEnv.GCAction { Reference = luaReference, IsDelegate = is_delegate });
                }
#if THREAD_SAFE || HOTFIX_ENABLE
            }
#endif
        }
        disposed = true;
    }
}

调用Dispose接口,里面通知了translator此luaBase需要被释放,而translator则开始对lua注册表进行pop工作,尤其不要忘记之前的reference存储工作,也是要进行解绑的,如最后一句LuaAPI.lua_unref操作:

public void ReleaseLuaBase(RealStatePtr L, int reference, bool is_delegate)
{
    if(is_delegate)
    {
        LuaAPI.xlua_rawgeti(L, LuaIndexes.LUA_REGISTRYINDEX, reference);
        if (LuaAPI.lua_isnil(L, -1))
        {
            LuaAPI.lua_pop(L, 1);
        }
        else
        {
            LuaAPI.lua_pushvalue(L, -1);
            LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
            if (LuaAPI.lua_type(L, -1) == LuaTypes.LUA_TNUMBER && LuaAPI.xlua_tointeger(L, -1) == reference) //
            {
                //UnityEngine.Debug.LogWarning("release delegate ref = " + luaReference);
                LuaAPI.lua_pop(L, 1);// pop LUA_REGISTRYINDEX[func]
                LuaAPI.lua_pushnil(L);
                LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); // LUA_REGISTRYINDEX[func] = nil
            }
            else //another Delegate ref the function before the GC tick
            {
                LuaAPI.lua_pop(L, 2); // pop LUA_REGISTRYINDEX[func] & func
            }
        }

        LuaAPI.lua_unref(L, reference);
        delegate_bridges.Remove(reference);
    }
    else
    {
        LuaAPI.lua_unref(L, reference);
    }
}

相关推荐

  1. Xlua分析Lua调用C#

    2024-02-04 06:10:02       33 阅读
  2. Xlua分析C#调用Lua

    2024-02-04 06:10:02       25 阅读
  3. xlua源码分析(六) C#与lua的交互总结

    2024-02-04 06:10:02       41 阅读
  4. Lua 如何在Lua调用C/C++函数

    2024-02-04 06:10:02       22 阅读
  5. 39、Lua调用C函数(lua-5.2.3)

    2024-02-04 06:10:02       13 阅读
  6. LUA 调用c#关于c#报错时lua调用堆栈的监听

    2024-02-04 06:10:02       25 阅读
  7. 轻量脚本语言Lua的配置与c++调用

    2024-02-04 06:10:02       19 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-04 06:10:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-04 06:10:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-04 06:10:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-04 06:10:02       20 阅读

热门阅读

  1. 数组和List之间的相互转换

    2024-02-04 06:10:02       25 阅读
  2. 2024.2.3

    2024.2.3

    2024-02-04 06:10:02      25 阅读
  3. 开源模型应用落地-业务优化篇(四)

    2024-02-04 06:10:02       28 阅读
  4. Node.js版本管理工具之_GNVM

    2024-02-04 06:10:02       26 阅读
  5. vue实现二维数组表格渲染

    2024-02-04 06:10:02       33 阅读
  6. 超越原生:探索Node.js中最佳文件系统三方库

    2024-02-04 06:10:02       29 阅读
  7. 类银河恶魔城学习记录1-8 PlayerDash补全 P35

    2024-02-04 06:10:02       28 阅读
  8. 四边形循环与生命的关系猜想

    2024-02-04 06:10:02       25 阅读