CLR绑定 — ILRuntime (ourpalm.github.io)
CLR绑定就是将热更dll内一些需要对CLR接口反射才能调用的主工程的方法,转化为ILRuntime自定义的方法,像Xlua也有类似的绑定机制,目的是为了降低反射性能开销和额外的GC Allocate。
在新版的ILRuntime中,会自动分析热更dll中有哪些地方使用到了必须添加绑定的Type,然后生成绑定代码。
需要注意的是,生成绑定代码之前需要注册所有的跨域继承适配器,否则ILRuntime生成绑定代码时无法正确抓取应用
编辑器工具
在Assets文件夹内新建ILRuntime文件夹,并在其中新建Editor文件夹,在其中新建ILRuntimeCLRBinding
文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| using UnityEditor; using ILRuntime.Runtime.CLRBinding; using ILRuntime.Runtime.Enviorment; using System.IO;
public class ILRuntimeCLRBinding { [MenuItem("ILRuntime/Generate CLR Binding Code by Analysis")] static void GenerateCLRBindingByAnalysis() { AppDomain domain = new AppDomain(); using(FileStream fs = new FileStream("Assets/GameData/Data/HotFix/Hotfix.dll.txt",FileMode.Open,FileAccess.Read)) { domain.LoadAssembly(fs); InitILRuntime(domain); BindingCodeGenerator.GenerateBindingCode(domain, "Assets/ILRuntime/Generated"); AssetDatabase.Refresh(); } } static void InitILRuntime(AppDomain domain) { domain.RegisterCrossBindingAdaptor(new InheritanceAdaptor()); } }
|
初始化绑定
在CLR绑定代码生成之后,需要将这些绑定代码注册到AppDomain中才能使CLR绑定生效,但是一定要记得将CLR绑定的注册写在CLR重定向的注册后面,因为同一个方法只能被重定向一次,只有先注册的那个才能生效。
在ILRuntimeManager
的InitializeILRuntime
方法后面加上
1 2 3 4 5
| void InitializeILRuntime() { ILRuntime.Runtime.Generated.CLRBindings.Initialize(m_AppDomain); }
|