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 typecastersMap[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_ENABLElock (luaEnv.luaEnvLock){
#endifvar 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_0if (!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_ENABLElock (luaEnv.luaEnvLock){
#endifbool 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);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/665667.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

算法42:天际线问题(力扣218题)---线段树

218. 天际线问题 城市的 天际线 是从远处观看该城市中所有建筑物形成的轮廓的外部轮廓。给你所有建筑物的位置和高度&#xff0c;请返回 由这些建筑物形成的 天际线 。 每个建筑物的几何信息由数组 buildings 表示&#xff0c;其中三元组 buildings[i] [lefti, righti, heig…

【Spring连载】使用Spring Data访问Redis(九)----Redis流 Streams

【Spring连载】使用Spring Data访问Redis&#xff08;九&#xff09;----Redis流 Streams 一、追加Appending二、消费Consuming2.1 同步接收Synchronous reception2.2 通过消息监听器容器进行异步接收Asynchronous reception through Message Listener Containers2.2.1 命令式I…

【学网攻】 第(20)节 -- 网络端口地址转换NAPT配置

系列文章目录 提示&#xff1a;这里可以添加系列文章的所有文章的目录&#xff0c;目录需要自己手动添加 例如&#xff1a;第一章 Python 机器学习入门之pandas的使用 提示&#xff1a;写完文章后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目…

Elasticsearch重建索引-修改索引字段类型

如果不允许修改索引字段类型&#xff0c;只能重建索引 步骤 新建一个索引数据迁移删除旧索引别名引用 目录 1、准备工作1.1、查看版本号1.2、创建旧索引1.3、添加两条数据1.4、查看数据 2、新建一个索引2.1、查看旧索引的mapping2.2、新建索引 3、数据迁移3.1、使用异步任务迁…

C语言应用实例——贪吃蛇

&#xff08;图片由AI生成&#xff09; 0.贪吃蛇游戏背景 贪吃蛇游戏&#xff0c;最早可以追溯到1976年的“Blockade”游戏&#xff0c;是电子游戏历史上的一个经典。在这款游戏中&#xff0c;玩家操作一个不断增长的蛇&#xff0c;目标是吃掉出现在屏幕上的食物&#xff0c…

探究 MySQL 中使用 where 1=1 是否存在性能影响

文章目录 前言聊聊 mybatis 中多条件拼接的两种常规写法where 11使用 <where> 标签 性能影响where 11<where> 标签 总结个人简介 前言 最近在项目中使用 mybatis 写 SQL 使用了 where 11 来简化多条件拼接的写法&#xff0c;案例如下&#xff0c;借此聊聊多条件拼…

CTF(5)

一、[SWPUCTF 2021 新生赛]ez_caesar 1、题目 import base64 def caesar(plaintext):str_list list(plaintext)i 0while i < len(plaintext):if not str_list[i].isalpha():str_list[i] str_list[i]else:a "A" if str_list[i].isupper() else "a"…

C++学习Day01之初识C++ Helloworld

目录 一、程序二、输出三、分析与总结 一、程序 #include <iostream> //标准输入输出流 i - input 输入 o - output 输出 stream 流 相当于 stdio.h using namespace std; //使用 标准 命名空间 //程序入口函数 int main() {// cout 标准输出流对象// <&l…

Java学习-案例-ATM系统

案例ATM系统 大致思路&#xff1a; 实现功能&#xff1a; 案例代码&#xff1a; Account类&#xff1a; packageatmDemo; publicclassAccount{ privateStringcardId; privateStringuserName; privatecharsex; privateStringpassWord; privatedoublemoney; privatedoublelimit; …

ICLR 2024 | MolGen: 化学反馈引导的预训练分子生成

MolGen: 化学反馈引导的预训练分子生成 英文题目&#xff1a;Domain-Agnostic Molecular Generation with Chemical Feedback 发表会议&#xff1a;ICLR 2024 论文链接&#xff1a;https://arxiv.org/abs/2301.11259 代码链接&#xff1a;https://github.com/zjunlp/MolGen 目录…

可解释性AI(XAI):构建透明和值得信赖的决策过程

可解释性AI&#xff08;XAI&#xff09;旨在提高人工智能系统的透明度和可理解性&#xff0c;使人们更好地理解AI的决策过程和原理。随着AI技术的广泛应用&#xff0c;XAI成为了一个备受关注的重要领域。它不仅有助于建立人们对AI的信任&#xff0c;还可以帮助解决AI伦理和偏见…

Python flask 表单详解

文章目录 1 概述1.1 request 对象 2 示例2.1 目录结构2.2 student.html2.3 result.html2.4 app.py 1 概述 1.1 request 对象 作用&#xff1a;来自客户端网页的数据作为全局请求对象发送到服务器request 对象的重要属性如下&#xff1a; 属性解释form字典对象&#xff0c;包…

Android状态栏/通知栏图标白底问题

问题及现象 从android L版本开始&#xff0c;为了统一图标样式&#xff0c;会将通知栏、状态栏等显示图标处统一为白底或黑底&#xff0c;以促使开发人员规范图标设计。 从现象看&#xff0c;状态栏会显示一个白底的方框&#xff1b;下拉通知栏展开时的图标为白底方框加圆框…

HCIP-Datacom(H12-821)91-100题解析

有需要完整题库的同学可以私信博主&#xff0c;博主看到会回复将文件发给你&#xff01;&#xff08;麻烦各位同学给博主推文点赞关注和收藏哦&#xff09; 91、下面关于AS PATH的描述&#xff0c;错误的 A.当路由器中存在两条或者两条以上的到同一目的地的路由时&#xff0c;…

IEC104 S帧超时判定客户与服务端不匹配造成的异常链接问题分析

2、通过ss命令发现确有链接端口变化&#xff0c;与设备约一天一次的重连&#xff0c;通过抓包&#xff08;tcpdump -vvv -nn port 1001 -w 0926.cap&#xff09;分析得以下现象 2.1、异常情况时未对设备的I帧均匀的回S帧进行确认&#xff0c;正常情况时均匀的回S帧进行确认 2.…

优化 React:理解 DOM Diffing 算法及关键的 key 属性

优化 React&#xff1a;理解 DOM Diffing 算法及关键的 key 属性 DOM 的 Diffing 算法和 Key 的作用 在 React 中&#xff0c;DOM 的 Diffing&#xff08;差异比较&#xff09;算法是一种优化手段&#xff0c;用于确定虚拟 DOM 树与实际 DOM 树之间的差异&#xff0c;并仅更新…

酷开科技依托酷开系统新剧热播,引领潮流风向

随着科技的不断发展&#xff0c;智能电视已经成为了家庭娱乐的主流&#xff0c;是消费者居家休闲放松的好帮手。其中&#xff0c;作为国内智能电视操作系统领军者的酷开系统&#xff0c;一直致力于为消费者提供丰富的内容和贴心的体验。近日&#xff0c;酷开系统新剧热播&#…

仰暮计划|“每次他们吃饭,出来散步,都是背着枪,枪都是装满子弹上好膛,时刻准备着作战和反击”

20世纪70年代中叶&#xff0c;越南结束抗美战争、实现国家统一后&#xff0c;把中国视为“头号敌人”&#xff0c;中越关系急剧恶化&#xff0c;中国边疆的和平、安定和人民的生命财产受到严重威胁。在此情况下&#xff0c;1979年2月17日&#xff0c;遵照中央军委命令&#xff…

车载测试Vector工具CANoe——常见问题汇总(中)

车载测试Vector工具CANoe——常见问题汇总(中) 我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师(Wechat:gongkenan2013)。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 屏蔽力是信息过载时代一个人的特殊竞争力,任何消耗你的人和事,多看一…

【兼容认证】白鲸开源与银河麒麟高级服务器操作系统成功通过测试

2024年1月2日&#xff0c;北京白鲸开源科技有限公司&#xff08;以下简称"白鲸开源"&#xff09;荣幸宣布&#xff0c;白鲸开源旗下产品 WhaleStudio V2.4 已成功通过与麒麟软件有限公司旗下的银河麒麟高级服务器操作系统产品的兼容性测试。 麒麟软件有限公司的银河麒…