主頁 > .NET開發 > 深入理解xLua基于IL代碼注入的熱更新原理

深入理解xLua基于IL代碼注入的熱更新原理

2021-10-30 06:01:12 .NET開發

目前大部分手游都會采用熱更新來解決應用商店審核周期長,無法滿足快節奏迭代的問題,另外熱更新能夠有效降低版本升級所需的資源大小,節省玩家的時間和流量,這也使其成為移動游戲的主流更新方式之一,

熱更新可以分為資源熱更和代碼熱更兩類,其中代碼熱更又包括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/ScriptAssemblies\Assembly-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#熱修復,

參考

  • 深入xLua實作原理之Lua如何呼叫C#
  • 深入xLua實作原理之C#如何呼叫Lua
  • 如何評價騰訊在Unity下的xLua(開源)熱更方案? - 車雄生的回答 - 知乎
  • 理解IL
  • xlua注入原始碼解讀
  • Unity 熱更新為啥用Lua
  • 熱更新
作者:iwiniwin 出處:http://www.cnblogs.com/iwiniwin/ 本文為博主原創文章,轉載請附上原文出處鏈接和本宣告,

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341657.html

標籤:.NET技术

上一篇:深入理解xLua基于IL代碼注入的熱更新原理

下一篇:MahApps.Metro 源代碼的編譯,以及 Demo 的運行

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more