zoukankan      html  css  js  c++  java
  • 深入理解xLua基于IL代码注入的热更新原理

    目前大部分手游都会采用热更新来解决应用商店审核周期长,无法满足快节奏迭代的问题。另外热更新能够有效降低版本升级所需的资源大小,节省玩家的时间和流量,这也使其成为移动游戏的主流更新方式之一。

    热更新可以分为资源热更和代码热更两类,其中代码热更又包括Lua热更和C#热更。Lua作为一种轻量小巧的脚本语言,由Lua虚拟机解释执行。所以Lua热更通过简单的源代码文件替换即可完成。反观C#的整个编译执行过程是先通过编译器将C#编译成IL(Intermediate Language),再由CLR(Common Language Runtime)将IL编译成平台相关的二进制机器码进行执行。

    在JIT(Just in time)模式下可以做到运行时将IL编译成机器码,此时如果C#利用反射动态加载程序集,则通过替换DLL文件即可完成C#热更。虽然Android是支持JIT的,但IOS并不支持,IOS仅支持AOT(Ahead of time)模式。且Mono在IOS平台上使用的是Full AOT模式,会在程序运行前就将IL编译成机器码。如果使用反射执行DLL文件,就会触发Mono的JIT编译器,而Full AOT模式又不允许JIT,就会报以下错误

    ExecutionEngineException: Attempting to JIT compile method '...' while running with --aot-only.
    

    所以C#通过反射热更的方式在不同平台并不通用。

    基于IL代码注入热更

    最后只剩下基于IL代码注入的C#热更方案了,这也是xLua框架热更所采用的方案。它的基本思想是,对于一个类

    public class TestXLua
    {
        public int Add(int a, int b)
        {
            return a - b;
        }
    }
    

    通过在IL层面为其注入代码,使其变成类似这样

    public class TestXLua
    {
        static Func<object, int, int, int> hotfix_Add = null;
        int Add(int a, int b)
        {
            if (hotfix_Add != null) return hotfix_Add(this, a, b);
            return a - b;
        }
    }
    

    然后通过Lua编写补丁,使hotfix_Add指向一个lua的适配函数,从而达到替换原C#函数,实现更新的目的。

    根据xLua热更新操作指南,使用xLua热更主要有以下4个步骤

    1、打开该特性
    
    添加HOTFIX_ENABLE宏,(在Unity3D的File->Build Setting->Scripting Define Symbols下添加)。编辑器、各手机平台这个宏要分别设置!如果是自动化打包,要注意在代码里头用API设置的宏是不生效的,需要在编辑器设置。
    
    2、执行XLua/Generate Code菜单。
    
    3、注入,构建手机包这个步骤会在构建时自动进行,编辑器下开发补丁需要手动执行"XLua/Hotfix Inject In Editor"菜单。打印“hotfix inject finish!”或者“had injected!”才算成功,否则会打印错误信息。
    
    4、使用xlua.hotfix或util.hotfix_ex打补丁
    

    接下来将逐个分析上述步骤背后都做了些什么,是如何一步步基于IL代码注入实现热更的

    打开HOTFIX_ENABLE宏

    HOTFIX_ENABLE是xLua定义启用热更的一个宏,添加这个宏主要有两个作用

    1. 在编辑器中出现"XLua/Hotfix Inject In Editor"菜单,通过该菜单可以手动执行代码注入
    2. 利用HOTFIX_ENABLE进行了条件编译,定义了一些只有使用热更时才需要的方法。例如DelegateBridge.cs中的部分方法,这些方法会在针对泛型方法进行IL注入时用到
      // DelegateBridge.cs
      #if HOTFIX_ENABLE
          private int _oldTop = 0;
          private Stack<int> _stack = new Stack<int>();
          public void InvokeSessionStart()
          {
              // ...
          }
          public void Invoke(int nRet)
          {
              // ...
          }
          public void InvokeSessionEnd()
          {
              // ...
          }
          // ...
      #endif
      

    生成代码

    生成代码的作用,主要是为标记有Hotfix特性的方法生成对应的匹配函数。以添加了Hotfix特性的TestXLua为例

    // 测试用 TestXLua.cs
    [Hotfix]
    public class TestXLua
    {
        public int Add(int a, int b)
        {
            return a - b;  // 这里的Add方法故意写成减法,后面通过热更新修复
        }
    }
    

    会在配置的Gen目录下生成DelegatesGensBridge.cs文件,其中有为TestXLua.Add生成的对应的匹配函数__Gen_Delegate_Imp1

    // DelegatesGensBridge.cs
    public partial class DelegateBridge : DelegateBridgeBase
    {
        // ...
        public int __Gen_Delegate_Imp1(object p0, int p1, int p2)
        {
    #if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
    #endif
                RealStatePtr L = luaEnv.rawL;
                int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
                ObjectTranslator translator = luaEnv.translator;
                translator.PushAny(L, p0);
                LuaAPI.xlua_pushinteger(L, p1);
                LuaAPI.xlua_pushinteger(L, p2);
                
                PCall(L, 3, 1, errFunc);
                
                
                int __gen_ret = LuaAPI.xlua_tointeger(L, errFunc + 1);
                LuaAPI.lua_settop(L, errFunc - 1);
                return  __gen_ret;
    #if THREAD_SAFE || HOTFIX_ENABLE
            }
    #endif
        }
        // ...
    }
    

    为什么需要生成对应的匹配函数呢?这是因为xLua就是通过将该C#函数替换成Lua函数来实现热更的。也就是说,热更后就会出现C#调用Lua函数的情况,而C#想要调用Lua函数,就需要用到生成的匹配函数。具体流程是,调用传递给C#的Lua函数时,相当于调用以"__Gen_Delegate_Imp"开头的生成函数,这个生成函数负责参数压栈,并通过保存的索引获取到真正的Lua function,然后使用lua_pcall完成Lua function的调用。

    关于C#如何调用Lua方法的详细介绍可以参考这篇文章

    注入

    点击"XLua/Hotfix Inject In Editor"菜单后会开始注入代码。将触发HotfixInject方法,内部再通过xLua提供的工具XLuaHotfixInject.exe来完成代码注入。应该是为了避免文件占用问题,所以直接提供了exe工具。同时IL代码注入需要用到Mono.Cecil库,这样也避免了每个项目都要额外集成这个库。

    // Hotfix.cs
    [MenuItem("XLua/Hotfix Inject In Editor", false, 3)]
    public static void HotfixInject()
    {
        HotfixInject("./Library/ScriptAssemblies");
    }
    

    通过查看exe工具源码可知,最终实际完成代码注入的还是在Hotfix.cs文件中定义的重载方法HotfixInject,相关代码通过XLUA_GENERAL宏做了条件编译。

    // Hotfix.cs
    public static void HotfixInject(string injectAssemblyPath, string xluaAssemblyPath, IEnumerable<string> searchDirectorys, string idMapFilePath, Dictionary<string, int> hotfixConfig)
    {
        AssemblyDefinition injectAssembly = null;
        AssemblyDefinition xluaAssembly = null;
        // ...
        injectAssembly = readAssembly(injectAssemblyPath);
        
        // injected flag check
        if (injectAssembly.MainModule.Types.Any(t => t.Name == "__XLUA_GEN_FLAG"))
        {
            Info(injectAssemblyPath + " had injected!");
            return;
        }
        // 添加一个新的类型定义,以标记已注入
        injectAssembly.MainModule.Types.Add(new TypeDefinition("__XLUA_GEN", "__XLUA_GEN_FLAG", ILRuntime.Mono.Cecil.TypeAttributes.Class,
            injectAssembly.MainModule.TypeSystem.Object));
    
        xluaAssembly = (injectAssemblyPath == xluaAssemblyPath || injectAssembly.MainModule.FullyQualifiedName == xluaAssemblyPath) ? 
            injectAssembly : readAssembly(xluaAssemblyPath);
    
        Hotfix hotfix = new Hotfix();
        hotfix.Init(injectAssembly, xluaAssembly, searchDirectorys, hotfixConfig);
    
        //var hotfixDelegateAttributeType = assembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixDelegateAttribute");
        var hotfixAttributeType = xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixAttribute");
        var toInject = (from module in injectAssembly.Modules from type in module.Types select type).ToList();  // injectAssembly中的各个类型
        foreach (var type in toInject)
        {
            if (!hotfix.InjectType(hotfixAttributeType, type))
            {
                return;
            }
        }
        Directory.CreateDirectory(Path.GetDirectoryName(idMapFilePath));
        hotfix.OutputIntKeyMapper(new FileStream(idMapFilePath, FileMode.Create, FileAccess.Write));
        File.Copy(idMapFilePath, idMapFilePath + "." + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
        // 写入对程序集的修改
        writeAssembly(injectAssembly, injectAssemblyPath);
        Info(injectAssemblyPath + " inject finish!");
        // ...
    }
    

    其中,injectAssemblyPath表示要注入的程序集,例如./Library/ScriptAssembliesAssembly-CSharp.dll。xluaAssemblyPath表示LuaEnv所在程序集的完全限定路径,一般情况下和injectAssemblyPath相同。HotfixInject的主要任务是遍历injectAssembly中的所有类型,通过InjectType依次对它们进行代码注入

    // Hotfix.cs
    public bool InjectType(TypeReference hotfixAttributeType, TypeDefinition type)
    {
        foreach(var nestedTypes in type.NestedTypes)
        {
            if (!InjectType(hotfixAttributeType, nestedTypes))
            {
                return false;
            }
        }
        if (type.Name.Contains("<") || type.IsInterface || type.Methods.Count == 0) // skip anonymous type and interface
        {
            return true;
        }
        CustomAttribute hotfixAttr = type.CustomAttributes.FirstOrDefault(ca => ca.AttributeType == hotfixAttributeType);  // 获取type上的HotfixAttribute
        HotfixFlagInTool hotfixType;
        // 仅对带有HotfixAttribute的类型或hotfixCfg中有配置的类型进行注入
        if (hotfixAttr != null)
        {
            hotfixType = (HotfixFlagInTool)(int)hotfixAttr.ConstructorArguments[0].Value;  // 获取HotfixAttribute构造函数的第一个参数,HotfixFlag
        }
        else
        {
            if (!hotfixCfg.ContainsKey(type.FullName))
            {
                return true;
            }
            hotfixType = (HotfixFlagInTool)hotfixCfg[type.FullName];
        }
    
        // 通过HotfixFlag的不同设定过滤要注入的方法
        bool ignoreProperty = hotfixType.HasFlag(HotfixFlagInTool.IgnoreProperty);
        bool ignoreCompilerGenerated = hotfixType.HasFlag(HotfixFlagInTool.IgnoreCompilerGenerated);
        bool ignoreNotPublic = hotfixType.HasFlag(HotfixFlagInTool.IgnoreNotPublic);
        bool isInline = hotfixType.HasFlag(HotfixFlagInTool.Inline);
        bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey);
        bool noBaseProxy = hotfixType.HasFlag(HotfixFlagInTool.NoBaseProxy);
        if (ignoreCompilerGenerated && type.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute"))  // 忽略由编译器生成的类型
        {
            return true;
        }
        if (isIntKey && type.HasGenericParameters)
        {
            throw new InvalidOperationException(type.FullName + " is generic definition, can not be mark as IntKey!");
        }
        //isIntKey = !type.HasGenericParameters;
    
        foreach (var method in type.Methods)
        {
            if (ignoreNotPublic && !method.IsPublic)
            {
                continue;
            }
            if (ignoreProperty && method.IsSpecialName && (method.Name.StartsWith("get_") || method.Name.StartsWith("set_")))  // 忽略属性
            {
                continue;
            }
            if (ignoreCompilerGenerated && method.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute"))
            {
                continue;
            }
            if (method.Name != ".cctor" && !method.IsAbstract && !method.IsPInvokeImpl && method.Body != null && !method.Name.Contains("<"))
            {
                //Debug.Log(method);
                if ((isInline || method.HasGenericParameters || genericInOut(method, hotfixType)) 
                    ? !injectGenericMethod(method, hotfixType) :
                    !injectMethod(method, hotfixType))
                {
                    return false;
                }
            }
        }
        // ...
    }
    

    InjectType的主要任务是遍历指定类型的所有方法(根据HotfixFlag会做一些过滤),依次对它们进行代码注入。注入方法有两个,一个是针对泛型方法的injectGenericMethod,一个是针对普通方法的injectMethod。两个方法逻辑是类似的,这里简单起见,就主要分析injectMethod方法

    // Hotfix.cs
    bool injectMethod(MethodDefinition method, HotfixFlagInTool hotfixType)
    {
        var type = method.DeclaringType;  // 方法所在类
        bool isFinalize = (method.Name == "Finalize" && method.IsSpecialName);
        MethodReference invoke = null;
        int param_count = method.Parameters.Count + (method.IsStatic ? 0 : 1);
        if (!findHotfixDelegate(method, out invoke, hotfixType))  // 找到与method匹配的生成方法,以__Gen_Delegate_Imp开头的
        {
            Error("can not find delegate for " + method.DeclaringType + "." + method.Name + "! try re-genertate code.");
            return false;
        }
        if (invoke == null)
        {
            throw new Exception("unknow exception!");
        }
    #if XLUA_GENERAL
        invoke = injectAssembly.MainModule.ImportReference(invoke);
    #else
        invoke = injectAssembly.MainModule.Import(invoke);
    #endif
        FieldReference fieldReference = null;
        VariableDefinition injection = null;
        // IntKey是xLua的标志位,可以控制不生成静态字段,而是把所有注入点放到一个数组集中管理。这里可以先忽略,主要看 is not IntKey的逻辑
        bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey) && !type.HasGenericParameters && isTheSameAssembly;  
        //isIntKey = !type.HasGenericParameters;
        if (!isIntKey)
        {
            injection = new VariableDefinition(invoke.DeclaringType);  // 新创建一个XLua.DelegateBridge类型的变量
            method.Body.Variables.Add(injection);
    
            var luaDelegateName = getDelegateName(method);  // 获取将要添加的静态变量的名称,这个静态变量用于保存Lua补丁设置的方法
            if (luaDelegateName == null)
            {
                Error("too many overload!");
                return false;
            }
    
            FieldDefinition fieldDefinition = new FieldDefinition(luaDelegateName, ILRuntime.Mono.Cecil.FieldAttributes.Static | ILRuntime.Mono.Cecil.FieldAttributes.Private,
                invoke.DeclaringType);  // 创建一个静态XLua.DelegateBridge变量,用于保存Lua补丁设置的方法
            type.Fields.Add(fieldDefinition);  // 给type添加一个luaDelegateName静态字段,这个字段值在调用xlua.hotfix时会赋值
            fieldReference = fieldDefinition.GetGeneric();
        }
    
        bool ignoreValueType = hotfixType.HasFlag(HotfixFlagInTool.ValueTypeBoxing);
    
        var insertPoint = method.Body.Instructions[0];
        // //获取IL处理器
        var processor = method.Body.GetILProcessor();
    
        if (method.IsConstructor)
        {
            insertPoint = findNextRet(method.Body.Instructions, insertPoint);  // 获取到下一个Ret指令
        }
    
        Dictionary<Instruction, Instruction> originToNewTarget = new Dictionary<Instruction, Instruction>();
        HashSet<Instruction> noCheck = new HashSet<Instruction>();
    
        // 真正的IL代码注入逻辑。通过Mono.Cecil库的API插入一些IL指令
        while (insertPoint != null)
        {
            Instruction firstInstruction;
            if (isIntKey)
            {
                // ...
            }
            else
            {
                firstInstruction = processor.Create(OpCodes.Ldsfld, fieldReference);  // 加载静态域fieldReference,即luaDelegateName字段
                processor.InsertBefore(insertPoint, firstInstruction);
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Stloc, injection));  // 存储本地变量,将injection变量的值设置为luaDelegateName字段的值
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));  // 加载本地变量
            }
    
            // Brfalse表示栈上的值为 false/null/0 时发生跳转,如果injection的值为空,就调转到insertPoint,那通过InsertBefore插入的指令就都会被跳过了
            var jmpInstruction = processor.Create(OpCodes.Brfalse, insertPoint);  
            processor.InsertBefore(insertPoint, jmpInstruction);
    
            if (isIntKey)
            {
                // ...
            }
            else
            {
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));  // 再加载一次injection的值
            }
            // 加载参数
            for (int i = 0; i < param_count; i++)
            {
                if (i < ldargs.Length)
                {
                    processor.InsertBefore(insertPoint, processor.Create(ldargs[i]));  // 加载第i个参数
                }
                else if (i < 256)
                {
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_S, (byte)i));
                }
                else
                {
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg, (short)i));
                }
                if (i == 0 && !method.IsStatic && type.IsValueType)
                {
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldobj, type));  // 加载对象
                }
                // ...
            }
    
            // 插入方法调用指令
            processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, invoke));  // 调用injection处值(DelegateBridge对象)的方法invoke(__Gen_Delegate_Imp开头的方法)
    
            if (!method.IsConstructor && !isFinalize)
            {
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ret));  // 插入返回指令
            }
    
            if (!method.IsConstructor)
            {
                break;
            }
            else
            {
                originToNewTarget[insertPoint] = firstInstruction;
                noCheck.Add(jmpInstruction);
            }
            insertPoint = findNextRet(method.Body.Instructions, insertPoint);
        }
        // ...
    }
    

    injectMethod的主要逻辑是对于要注入的方法method,先找到与其相匹配的以__Gen_Delegate_Imp开头的生成方法,然后通过IL操作为method所在类添加一个DelegateBridge类型的静态变量(变量名通过getDelegateName方法获得)。并在method方法头部插入IL指令逻辑:判断静态变量是否不为空,如果不为空,则调用DelegateBridge变量的以__Gen_Delegate_Imp开头的生成方法并直接返回不再执行原逻辑。这个生成方法在打补丁后对应的就是Lua函数。

    打补丁

    xlua可以通过xlua.hotfix或xlua.hotfix_ex将C#函数逻辑替换成Lua函数。例如替换TestXLua.Add方法来修复其求和算法的错误

    -- lua测试文件
    xlua.hotfix(CS.TestXLua, "Add", function(self, a, b)
        return a + b  -- 修复成正确的加法
    end)
    

    xlua.hotfix的定义在LuaEnv.cs文件中,其中cs表示要修复的类,field表示要修复的变量名,func表示对应的修复函数

    -- LuaEnv.cs
    xlua.hotfix = function(cs, field, func)
        if func == nil then func = false end
        local tbl = (type(field) == 'table') and field or {[field] = func}
        for k, v in pairs(tbl) do
            local cflag = ''
            if k == '.ctor' then
                cflag = '_c'
                k = 'ctor'
            end
            local f = type(v) == 'function' and v or nil
            -- cflag .. '__Hotfix0_'..k 对应了前面C#代码中的 luaDelegateName
            xlua.access(cs, cflag .. '__Hotfix0_'..k, f) -- at least one
            pcall(function()
                for i = 1, 99 do
                    xlua.access(cs, cflag .. '__Hotfix'..i..'_'..k, f)
                end
            end)
        end
        xlua.private_accessible(cs)
    end
    

    主要逻辑是,先根据一定规则计算得到真正的C#变量名,这个变量名与前面的getDelegateName方法得到的变量名相同。例如在修复TestXLua.Add的例子中,这个变量名就叫做"__Hotfix0_Add"。然后通过xlua.access方法为这个变量设置对应的Lua修复函数

    // StaticLuaCallbacks.cs
    public static int XLuaAccess(RealStatePtr L)
    {
        try
        {
            ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
            Type type = getType(L, translator, 1);  // 获取第一个参数的类型
            object obj = null;
            if (type == null && LuaAPI.lua_type(L, 1) == LuaTypes.LUA_TUSERDATA)
            {
                obj = translator.SafeGetCSObj(L, 1);
                if (obj == null)
                {
                    return LuaAPI.luaL_error(L, "xlua.access, #1 parameter must a type/c# object/string");
                }
                type = obj.GetType();
            }
    
            if (type == null)
            {
                return LuaAPI.luaL_error(L, "xlua.access, can not find c# type");
            }
    
            string fieldName = LuaAPI.lua_tostring(L, 2);
    
            BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
    
            if (LuaAPI.lua_gettop(L) > 2) // set  设置字段值
            {
                // 设置字段(参数2)值为参数3
                var field = type.GetField(fieldName, bindingFlags);
                if (field != null)
                {
                    field.SetValue(obj, translator.GetObject(L, 3, field.FieldType));
                    return 0;
                }
                var prop = type.GetProperty(fieldName, bindingFlags);
                if (prop != null)
                {
                    prop.SetValue(obj, translator.GetObject(L, 3, prop.PropertyType), null);
                    return 0;
                }
            }
            else
            {
                // 获取字段(参数2)值
                var field = type.GetField(fieldName, bindingFlags);
                if (field != null)
                {
                    translator.PushAny(L, field.GetValue(obj));
                    return 1;
                }
                var prop = type.GetProperty(fieldName, bindingFlags);
                if (prop != null)
                {
                    translator.PushAny(L, prop.GetValue(obj, null));
                    return 1;
                }
            }
            return LuaAPI.luaL_error(L, "xlua.access, no field " + fieldName);  // 没有找到fieldName字段,抛出异常
        }
        catch (Exception e)
        {
            return LuaAPI.luaL_error(L, "c# exception in xlua.access: " + e);
        }
    }
    

    xlua.access实际上调用的是StaticLuaCallbacks.cs的XLuaAccess方法。主要功能是设置或访问指定字段的值。我们主要看设置字段值的部分,参数数量大于2(参数1类型,参数2字段名,参数3要设置的值),就表示是要设置字段值。xlua.hotfix通过XLuaAccess是为"__Hotfix0_Add"静态字段设置了一个Lua函数,在C#中这个Lua函数对应的是DelegateBridge对象(其内部保存着Lua函数的索引),这也是为什么前面IL注入时是为类添加一个DelegateBridge类型的静态变量

    总结

    以修复TestXLua.Add函数为例来描述一下整个热更过程

    先通过Generate Code为TestXLua.Add生成与其声明相同的匹配函数"__Gen_Delegate_Imp1",这个匹配函数是被生成在DelegateBridge类中的。有了这个匹配函数,Lua函数就可以被传递到C#中。

    然后通过IL代码注入,为TestXLua添加一个名为"__Hotfix0_Add"的DelegateBridge类型的静态变量。并在原来的Add方法中注入判断静态变量是否不为空,如果不为空就调用静态变量所对应的Lua方法的逻辑。反编译已注入IL代码的Assembly-CSharp.dll,查看其中的TestXLua如下所示

    using System;
    using XLua;
    
    // Token: 0x02000016 RID: 22
    [Hotfix(HotfixFlag.Stateless)]
    public class TestXLua
    {
    	// Token: 0x06000051 RID: 81 RVA: 0x00002CE0 File Offset: 0x00000EE0
    	public int Add(int a, int b)
    	{
    		DelegateBridge _Hotfix0_Add = TestXLua.__Hotfix0_Add;
    		if (_Hotfix0_Add != null)
    		{
    			return _Hotfix0_Add.__Gen_Delegate_Imp1(this, a, b);
    		}
    		return a - b;
    	}
    
    	// Token: 0x06000052 RID: 82 RVA: 0x00002D14 File Offset: 0x00000F14
    	public TestXLua()
    	{
    		DelegateBridge c__Hotfix0_ctor = TestXLua._c__Hotfix0_ctor;
    		if (c__Hotfix0_ctor != null)
    		{
    			c__Hotfix0_ctor.__Gen_Delegate_Imp2(this);
    		}
    	}
    
    	// Token: 0x04000022 RID: 34
    	private static DelegateBridge __Hotfix0_Add;
    
    	// Token: 0x04000023 RID: 35
    	private static DelegateBridge _c__Hotfix0_ctor;
    }
    

    最后打补丁时通过xlua.hotfix为静态变量"__Hotfix0_Add"设置一个Lua函数。这样下次调用TestXLua.Add时,"__Hotfix0_Add"将不为空,此时将执行_Hotfix0_Add.__Gen_Delegate_Imp1,即调用设置的Lua函数,而不再执行原有逻辑。从而实现了C#热修复。

    参考

    作者:iwiniwin
    本文为博主原创文章,转载请附上原文出处链接和本声明。
  • 相关阅读:
    git初学
    Android中activity的四个启动模式
    onsaveInstanceState有关问题
    default activity not found的问题
    实现随手指移动
    入园第一天
    玩转Django2.0---Django笔记建站基础八(admin后台系统)
    玩转Django2.0---Django笔记建站基础七(表单与模型)
    玩转Django2.0---Django笔记建站基础六(模型与数据库)
    玩转Django2.0---Django笔记建站基础五(模板)
  • 原文地址:https://www.cnblogs.com/iwiniwin/p/15474919.html
Copyright © 2011-2022 走看看