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

热更新可以分为资源热更和代码热更两类,其中代码热更又包括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,就会报以下错误

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

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

基于IL代码注入热更

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

  1. public class TestXLua
  2. {
  3. public int Add(int a, int b)
  4. {
  5. return a - b;
  6. }
  7. }

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

  1. public class TestXLua
  2. {
  3. static Func<object, int, int, int> hotfix_Add = null;
  4. int Add(int a, int b)
  5. {
  6. if (hotfix_Add != null) return hotfix_Add(this, a, b);
  7. return a - b;
  8. }
  9. }

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

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

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

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

打开HOTFIX_ENABLE宏

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

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

生成代码

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

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

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

  1. // DelegatesGensBridge.cs
  2. public partial class DelegateBridge : DelegateBridgeBase
  3. {
  4. // ...
  5. public int __Gen_Delegate_Imp1(object p0, int p1, int p2)
  6. {
  7. #if THREAD_SAFE || HOTFIX_ENABLE
  8. lock (luaEnv.luaEnvLock)
  9. {
  10. #endif
  11. RealStatePtr L = luaEnv.rawL;
  12. int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
  13. ObjectTranslator translator = luaEnv.translator;
  14. translator.PushAny(L, p0);
  15. LuaAPI.xlua_pushinteger(L, p1);
  16. LuaAPI.xlua_pushinteger(L, p2);
  17. PCall(L, 3, 1, errFunc);
  18. int __gen_ret = LuaAPI.xlua_tointeger(L, errFunc + 1);
  19. LuaAPI.lua_settop(L, errFunc - 1);
  20. return __gen_ret;
  21. #if THREAD_SAFE || HOTFIX_ENABLE
  22. }
  23. #endif
  24. }
  25. // ...
  26. }

为什么需要生成对应的匹配函数呢?这是因为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库,这样也避免了每个项目都要额外集成这个库。

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

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

  1. // Hotfix.cs
  2. public static void HotfixInject(string injectAssemblyPath, string xluaAssemblyPath, IEnumerable<string> searchDirectorys, string idMapFilePath, Dictionary<string, int> hotfixConfig)
  3. {
  4. AssemblyDefinition injectAssembly = null;
  5. AssemblyDefinition xluaAssembly = null;
  6. // ...
  7. injectAssembly = readAssembly(injectAssemblyPath);
  8. // injected flag check
  9. if (injectAssembly.MainModule.Types.Any(t => t.Name == "__XLUA_GEN_FLAG"))
  10. {
  11. Info(injectAssemblyPath + " had injected!");
  12. return;
  13. }
  14. // 添加一个新的类型定义,以标记已注入
  15. injectAssembly.MainModule.Types.Add(new TypeDefinition("__XLUA_GEN", "__XLUA_GEN_FLAG", ILRuntime.Mono.Cecil.TypeAttributes.Class,
  16. injectAssembly.MainModule.TypeSystem.Object));
  17. xluaAssembly = (injectAssemblyPath == xluaAssemblyPath || injectAssembly.MainModule.FullyQualifiedName == xluaAssemblyPath) ?
  18. injectAssembly : readAssembly(xluaAssemblyPath);
  19. Hotfix hotfix = new Hotfix();
  20. hotfix.Init(injectAssembly, xluaAssembly, searchDirectorys, hotfixConfig);
  21. //var hotfixDelegateAttributeType = assembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixDelegateAttribute");
  22. var hotfixAttributeType = xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixAttribute");
  23. var toInject = (from module in injectAssembly.Modules from type in module.Types select type).ToList(); // injectAssembly中的各个类型
  24. foreach (var type in toInject)
  25. {
  26. if (!hotfix.InjectType(hotfixAttributeType, type))
  27. {
  28. return;
  29. }
  30. }
  31. Directory.CreateDirectory(Path.GetDirectoryName(idMapFilePath));
  32. hotfix.OutputIntKeyMapper(new FileStream(idMapFilePath, FileMode.Create, FileAccess.Write));
  33. File.Copy(idMapFilePath, idMapFilePath + "." + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
  34. // 写入对程序集的修改
  35. writeAssembly(injectAssembly, injectAssemblyPath);
  36. Info(injectAssemblyPath + " inject finish!");
  37. // ...
  38. }

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

  1. // Hotfix.cs
  2. public bool InjectType(TypeReference hotfixAttributeType, TypeDefinition type)
  3. {
  4. foreach(var nestedTypes in type.NestedTypes)
  5. {
  6. if (!InjectType(hotfixAttributeType, nestedTypes))
  7. {
  8. return false;
  9. }
  10. }
  11. if (type.Name.Contains("<") || type.IsInterface || type.Methods.Count == 0) // skip anonymous type and interface
  12. {
  13. return true;
  14. }
  15. CustomAttribute hotfixAttr = type.CustomAttributes.FirstOrDefault(ca => ca.AttributeType == hotfixAttributeType); // 获取type上的HotfixAttribute
  16. HotfixFlagInTool hotfixType;
  17. // 仅对带有HotfixAttribute的类型或hotfixCfg中有配置的类型进行注入
  18. if (hotfixAttr != null)
  19. {
  20. hotfixType = (HotfixFlagInTool)(int)hotfixAttr.ConstructorArguments[0].Value; // 获取HotfixAttribute构造函数的第一个参数,HotfixFlag
  21. }
  22. else
  23. {
  24. if (!hotfixCfg.ContainsKey(type.FullName))
  25. {
  26. return true;
  27. }
  28. hotfixType = (HotfixFlagInTool)hotfixCfg[type.FullName];
  29. }
  30. // 通过HotfixFlag的不同设定过滤要注入的方法
  31. bool ignoreProperty = hotfixType.HasFlag(HotfixFlagInTool.IgnoreProperty);
  32. bool ignoreCompilerGenerated = hotfixType.HasFlag(HotfixFlagInTool.IgnoreCompilerGenerated);
  33. bool ignoreNotPublic = hotfixType.HasFlag(HotfixFlagInTool.IgnoreNotPublic);
  34. bool isInline = hotfixType.HasFlag(HotfixFlagInTool.Inline);
  35. bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey);
  36. bool noBaseProxy = hotfixType.HasFlag(HotfixFlagInTool.NoBaseProxy);
  37. if (ignoreCompilerGenerated && type.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute")) // 忽略由编译器生成的类型
  38. {
  39. return true;
  40. }
  41. if (isIntKey && type.HasGenericParameters)
  42. {
  43. throw new InvalidOperationException(type.FullName + " is generic definition, can not be mark as IntKey!");
  44. }
  45. //isIntKey = !type.HasGenericParameters;
  46. foreach (var method in type.Methods)
  47. {
  48. if (ignoreNotPublic && !method.IsPublic)
  49. {
  50. continue;
  51. }
  52. if (ignoreProperty && method.IsSpecialName && (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))) // 忽略属性
  53. {
  54. continue;
  55. }
  56. if (ignoreCompilerGenerated && method.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute"))
  57. {
  58. continue;
  59. }
  60. if (method.Name != ".cctor" && !method.IsAbstract && !method.IsPInvokeImpl && method.Body != null && !method.Name.Contains("<"))
  61. {
  62. //Debug.Log(method);
  63. if ((isInline || method.HasGenericParameters || genericInOut(method, hotfixType))
  64. ? !injectGenericMethod(method, hotfixType) :
  65. !injectMethod(method, hotfixType))
  66. {
  67. return false;
  68. }
  69. }
  70. }
  71. // ...
  72. }

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

  1. // Hotfix.cs
  2. bool injectMethod(MethodDefinition method, HotfixFlagInTool hotfixType)
  3. {
  4. var type = method.DeclaringType; // 方法所在类
  5. bool isFinalize = (method.Name == "Finalize" && method.IsSpecialName);
  6. MethodReference invoke = null;
  7. int param_count = method.Parameters.Count + (method.IsStatic ? 0 : 1);
  8. if (!findHotfixDelegate(method, out invoke, hotfixType)) // 找到与method匹配的生成方法,以__Gen_Delegate_Imp开头的
  9. {
  10. Error("can not find delegate for " + method.DeclaringType + "." + method.Name + "! try re-genertate code.");
  11. return false;
  12. }
  13. if (invoke == null)
  14. {
  15. throw new Exception("unknow exception!");
  16. }
  17. #if XLUA_GENERAL
  18. invoke = injectAssembly.MainModule.ImportReference(invoke);
  19. #else
  20. invoke = injectAssembly.MainModule.Import(invoke);
  21. #endif
  22. FieldReference fieldReference = null;
  23. VariableDefinition injection = null;
  24. // IntKey是xLua的标志位,可以控制不生成静态字段,而是把所有注入点放到一个数组集中管理。这里可以先忽略,主要看 is not IntKey的逻辑
  25. bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey) && !type.HasGenericParameters && isTheSameAssembly;
  26. //isIntKey = !type.HasGenericParameters;
  27. if (!isIntKey)
  28. {
  29. injection = new VariableDefinition(invoke.DeclaringType); // 新创建一个XLua.DelegateBridge类型的变量
  30. method.Body.Variables.Add(injection);
  31. var luaDelegateName = getDelegateName(method); // 获取将要添加的静态变量的名称,这个静态变量用于保存Lua补丁设置的方法
  32. if (luaDelegateName == null)
  33. {
  34. Error("too many overload!");
  35. return false;
  36. }
  37. FieldDefinition fieldDefinition = new FieldDefinition(luaDelegateName, ILRuntime.Mono.Cecil.FieldAttributes.Static | ILRuntime.Mono.Cecil.FieldAttributes.Private,
  38. invoke.DeclaringType); // 创建一个静态XLua.DelegateBridge变量,用于保存Lua补丁设置的方法
  39. type.Fields.Add(fieldDefinition); // 给type添加一个luaDelegateName静态字段,这个字段值在调用xlua.hotfix时会赋值
  40. fieldReference = fieldDefinition.GetGeneric();
  41. }
  42. bool ignoreValueType = hotfixType.HasFlag(HotfixFlagInTool.ValueTypeBoxing);
  43. var insertPoint = method.Body.Instructions[0];
  44. // //获取IL处理器
  45. var processor = method.Body.GetILProcessor();
  46. if (method.IsConstructor)
  47. {
  48. insertPoint = findNextRet(method.Body.Instructions, insertPoint); // 获取到下一个Ret指令
  49. }
  50. Dictionary<Instruction, Instruction> originToNewTarget = new Dictionary<Instruction, Instruction>();
  51. HashSet<Instruction> noCheck = new HashSet<Instruction>();
  52. // 真正的IL代码注入逻辑。通过Mono.Cecil库的API插入一些IL指令
  53. while (insertPoint != null)
  54. {
  55. Instruction firstInstruction;
  56. if (isIntKey)
  57. {
  58. // ...
  59. }
  60. else
  61. {
  62. firstInstruction = processor.Create(OpCodes.Ldsfld, fieldReference); // 加载静态域fieldReference,即luaDelegateName字段
  63. processor.InsertBefore(insertPoint, firstInstruction);
  64. processor.InsertBefore(insertPoint, processor.Create(OpCodes.Stloc, injection)); // 存储本地变量,将injection变量的值设置为luaDelegateName字段的值
  65. processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); // 加载本地变量
  66. }
  67. // Brfalse表示栈上的值为 false/null/0 时发生跳转,如果injection的值为空,就调转到insertPoint,那通过InsertBefore插入的指令就都会被跳过了
  68. var jmpInstruction = processor.Create(OpCodes.Brfalse, insertPoint);
  69. processor.InsertBefore(insertPoint, jmpInstruction);
  70. if (isIntKey)
  71. {
  72. // ...
  73. }
  74. else
  75. {
  76. processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); // 再加载一次injection的值
  77. }
  78. // 加载参数
  79. for (int i = 0; i < param_count; i++)
  80. {
  81. if (i < ldargs.Length)
  82. {
  83. processor.InsertBefore(insertPoint, processor.Create(ldargs[i])); // 加载第i个参数
  84. }
  85. else if (i < 256)
  86. {
  87. processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_S, (byte)i));
  88. }
  89. else
  90. {
  91. processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg, (short)i));
  92. }
  93. if (i == 0 && !method.IsStatic && type.IsValueType)
  94. {
  95. processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldobj, type)); // 加载对象
  96. }
  97. // ...
  98. }
  99. // 插入方法调用指令
  100. processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, invoke)); // 调用injection处值(DelegateBridge对象)的方法invoke(__Gen_Delegate_Imp开头的方法)
  101. if (!method.IsConstructor && !isFinalize)
  102. {
  103. processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ret)); // 插入返回指令
  104. }
  105. if (!method.IsConstructor)
  106. {
  107. break;
  108. }
  109. else
  110. {
  111. originToNewTarget[insertPoint] = firstInstruction;
  112. noCheck.Add(jmpInstruction);
  113. }
  114. insertPoint = findNextRet(method.Body.Instructions, insertPoint);
  115. }
  116. // ...
  117. }

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方法来修复其求和算法的错误

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

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

  1. -- LuaEnv.cs
  2. xlua.hotfix = function(cs, field, func)
  3. if func == nil then func = false end
  4. local tbl = (type(field) == 'table') and field or {[field] = func}
  5. for k, v in pairs(tbl) do
  6. local cflag = ''
  7. if k == '.ctor' then
  8. cflag = '_c'
  9. k = 'ctor'
  10. end
  11. local f = type(v) == 'function' and v or nil
  12. -- cflag .. '__Hotfix0_'..k 对应了前面C#代码中的 luaDelegateName
  13. xlua.access(cs, cflag .. '__Hotfix0_'..k, f) -- at least one
  14. pcall(function()
  15. for i = 1, 99 do
  16. xlua.access(cs, cflag .. '__Hotfix'..i..'_'..k, f)
  17. end
  18. end)
  19. end
  20. xlua.private_accessible(cs)
  21. end

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

  1. // StaticLuaCallbacks.cs
  2. public static int XLuaAccess(RealStatePtr L)
  3. {
  4. try
  5. {
  6. ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
  7. Type type = getType(L, translator, 1); // 获取第一个参数的类型
  8. object obj = null;
  9. if (type == null && LuaAPI.lua_type(L, 1) == LuaTypes.LUA_TUSERDATA)
  10. {
  11. obj = translator.SafeGetCSObj(L, 1);
  12. if (obj == null)
  13. {
  14. return LuaAPI.luaL_error(L, "xlua.access, #1 parameter must a type/c# object/string");
  15. }
  16. type = obj.GetType();
  17. }
  18. if (type == null)
  19. {
  20. return LuaAPI.luaL_error(L, "xlua.access, can not find c# type");
  21. }
  22. string fieldName = LuaAPI.lua_tostring(L, 2);
  23. BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
  24. if (LuaAPI.lua_gettop(L) > 2) // set 设置字段值
  25. {
  26. // 设置字段(参数2)值为参数3
  27. var field = type.GetField(fieldName, bindingFlags);
  28. if (field != null)
  29. {
  30. field.SetValue(obj, translator.GetObject(L, 3, field.FieldType));
  31. return 0;
  32. }
  33. var prop = type.GetProperty(fieldName, bindingFlags);
  34. if (prop != null)
  35. {
  36. prop.SetValue(obj, translator.GetObject(L, 3, prop.PropertyType), null);
  37. return 0;
  38. }
  39. }
  40. else
  41. {
  42. // 获取字段(参数2)值
  43. var field = type.GetField(fieldName, bindingFlags);
  44. if (field != null)
  45. {
  46. translator.PushAny(L, field.GetValue(obj));
  47. return 1;
  48. }
  49. var prop = type.GetProperty(fieldName, bindingFlags);
  50. if (prop != null)
  51. {
  52. translator.PushAny(L, prop.GetValue(obj, null));
  53. return 1;
  54. }
  55. }
  56. return LuaAPI.luaL_error(L, "xlua.access, no field " + fieldName); // 没有找到fieldName字段,抛出异常
  57. }
  58. catch (Exception e)
  59. {
  60. return LuaAPI.luaL_error(L, "c# exception in xlua.access: " + e);
  61. }
  62. }

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如下所示

  1. using System;
  2. using XLua;
  3. // Token: 0x02000016 RID: 22
  4. [Hotfix(HotfixFlag.Stateless)]
  5. public class TestXLua
  6. {
  7. // Token: 0x06000051 RID: 81 RVA: 0x00002CE0 File Offset: 0x00000EE0
  8. public int Add(int a, int b)
  9. {
  10. DelegateBridge _Hotfix0_Add = TestXLua.__Hotfix0_Add;
  11. if (_Hotfix0_Add != null)
  12. {
  13. return _Hotfix0_Add.__Gen_Delegate_Imp1(this, a, b);
  14. }
  15. return a - b;
  16. }
  17. // Token: 0x06000052 RID: 82 RVA: 0x00002D14 File Offset: 0x00000F14
  18. public TestXLua()
  19. {
  20. DelegateBridge c__Hotfix0_ctor = TestXLua._c__Hotfix0_ctor;
  21. if (c__Hotfix0_ctor != null)
  22. {
  23. c__Hotfix0_ctor.__Gen_Delegate_Imp2(this);
  24. }
  25. }
  26. // Token: 0x04000022 RID: 34
  27. private static DelegateBridge __Hotfix0_Add;
  28. // Token: 0x04000023 RID: 35
  29. private static DelegateBridge _c__Hotfix0_ctor;
  30. }

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

参考

深入理解xLua基于IL代码注入的热更新原理的更多相关文章

  1. 另类Unity热更新大法:代码注入式补丁热更新

    对老项目进行热更新 项目用纯C#开发的? 眼看Unity引擎热火朝天,无数程序猿加入到了Unity开发的大本营. 一些老项目,在当时ulua/slua还不如今天那样的成熟,因此他们选择了全c#开发:也 ...

  2. 深入理解xLua热更新原理

    热更新简介 热更新是指在不需要重新编译打包游戏的情况下,在线更新游戏中的一些非核心代码和资源,比如活动运营和打补丁.热更新分为资源热更新和代码热更新两种,代码热更新实际上也是把代码当成资源的一种热更新 ...

  3. python基于函数替换的热更新原理介绍

    热更新即在不重启进程或者不离开Python interpreter的情况下使得被编辑之后的python源码能够直接生效并按照预期被执行新代码.平常开发中,热更能极大提高程序开发和调试的效率,在修复线上 ...

  4. 轻松理解webpack热更新原理

    一.前言 - webpack热更新 Hot Module Replacement,简称HMR,无需完全刷新整个页面的同时,更新模块.HMR的好处,在日常开发工作中体会颇深:节省宝贵的开发时间.提升开发 ...

  5. Emit 自动生成IL代码,注入代码

    Spring 框架中的注入代码,以及自动生成对接口的实现,则根据il代码注入 Emit学习(1)-Emit概览 一.Emit概述 Emit,可以称为发出或者产生.在Framework中,与Emit相关 ...

  6. C# IL中间代码注入实现切面编程

    背景及现状:之前分享的那篇“面向切面编程–渲染监控日志记录方案”中提供了利用RealProxy作为代理类来生成代理的面向切面的编程方法,那个方法可以实现面向切面编程进行日志记录,现在渲染主程序也是采用 ...

  7. XLua热更新用法全流程总结(所有容易出问题的点)

    Xlua热更新流程总结 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- 心分享.心创 ...

  8. Unity3D热更新之LuaFramework篇[09]--资源热更新与代码热更新的具体实现

    前言 在上一篇文章 Unity3D热更新之LuaFramework篇[08]--热更新原理及热更服务器搭建 中,我介绍了热更新的基本原理,并且着手搭建一台服务器. 本篇就做一个实战练习,真正的来实现热 ...

  9. 【技巧总结】Penetration Test Engineer[3]-Web-Security(SQL注入、XXS、代码注入、命令执行、变量覆盖、XSS)

    3.Web安全基础 3.1.HTTP协议 1)TCP/IP协议-HTTP 应用层:HTTP.FTP.TELNET.DNS.POP3 传输层:TCP.UDP 网络层:IP.ICMP.ARP 2)常用方法 ...

随机推荐

  1. 第24篇-虚拟机对象操作指令之getfield

    getfield指令表示获取指定类的实例域,并将其值压入栈顶.其格式如下: getstatic indexbyte1 indexbyte2 无符号数indexbyte1和indexbyte2构建为(i ...

  2. 1.docker概述及其历史

    一. 为什么会出现docker? 不用说, 肯定是时代进步的产物. 那么, 他为什么能火? 一定是解决了痛点问题. docker也不是一下子就火起来了, 他的火也是有一个过程的, 我们先来看看为什么会 ...

  3. ms sql 带自增列 带外键约束 数据导入导出

    1,生成建表脚本 选中要导的表,点右键-编写表脚本为-create到  ,生成建表脚本 2,建表(在新库),但不建外键关系 不要选中生成外键的那部分代码,只选择建表的代码 3,导数据,用SQL STU ...

  4. Ebiten-纯Golang开发的跨平台游戏引擎

    Go语言不是让你玩的啊喂! 昨天跟好基友聊开发的事,他说他等着闲下来的时候就用PYGame写个像那个最近挺火的"文X游X"一样的游戏.(没收广告费啊!) 基友突然嘲笑我:" ...

  5. 我爬取交通学博士付费的GIS资源,每年被动收入2w很简单?

    目录 1.背景介绍 2.技术路线 3.数据结果 4.数据分析 5.总结 6.后记 1.背景介绍 某周末闲来无事,顺手打开了CSDN,看到了一个人发布的收费GIS资源,售价是¥19.9,POI数据也有人 ...

  6. PHP中的日期相关函数(三)

    之前我们已经介绍过了 PHP 的一些相关的日期操作对象,今天我们就来学习剩下的那些面向过程的使用方式.当然,如果是和 DateTime 类中相似的方法我们就不再进行介绍了.另外,Date() 和 ti ...

  7. [原创]OpenEuler20.03安装配置PostgreSQL13.4详细图文版

    OpenEuler安装配置PostgreSQL 编写时间:2021年9月18日 作者:liupp 邮箱:liupp@88.com 序号 更新内容 更新日期 更新人 1 完成第一至三章内容编辑: 202 ...

  8. Docker系列(14)- Portainer可视化面板安装

    官网 https://documentation.portainer.io/v2.0-be/deploy/beinstalldocker/ 可视化 portainer docker run -d -p ...

  9. javascript / PHP [Design Patterns - Facade Pattern]

    This pattern involves a single class which provides simplified methods required by client and delega ...

  10. english note(6.10to6.16)

    6.10 http://www.51voa.com/VOA_Special_English/blackbeard-s-ship-comes-to-the-us-supreme-court-82217_ ...