ILHelper.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using ILRuntime.CLR.Method;
  5. using ILRuntime.CLR.TypeSystem;
  6. using ILRuntime.Runtime.Enviorment;
  7. using ILRuntime.Runtime.Generated;
  8. using ILRuntime.Runtime.Intepreter;
  9. using UnityEngine;
  10. namespace ETModel
  11. {
  12. public static class ILHelper
  13. {
  14. public static unsafe void InitILRuntime(ILRuntime.Runtime.Enviorment.AppDomain appDomain)
  15. {
  16. // 注册重定向函数
  17. // 注册委托
  18. appDomain.DelegateManager.RegisterMethodDelegate<List<object>>();
  19. appDomain.DelegateManager.RegisterMethodDelegate<AChannel, System.Net.Sockets.SocketError>();
  20. appDomain.DelegateManager.RegisterMethodDelegate<byte[], int, int>();
  21. appDomain.DelegateManager.RegisterMethodDelegate<IResponse>();
  22. appDomain.DelegateManager.RegisterMethodDelegate<Session, object>();
  23. appDomain.DelegateManager.RegisterMethodDelegate<Session, Packet>();
  24. appDomain.DelegateManager.RegisterMethodDelegate<Session>();
  25. appDomain.DelegateManager.RegisterMethodDelegate<ILTypeInstance>();
  26. CLRBindings.Initialize(appDomain);
  27. // 注册适配器
  28. Assembly assembly = typeof(Init).Assembly;
  29. foreach (Type type in assembly.GetTypes())
  30. {
  31. object[] attrs = type.GetCustomAttributes(typeof(ILAdapterAttribute), false);
  32. if (attrs.Length == 0)
  33. {
  34. continue;
  35. }
  36. object obj = Activator.CreateInstance(type);
  37. CrossBindingAdaptor adaptor = obj as CrossBindingAdaptor;
  38. if (adaptor == null)
  39. {
  40. continue;
  41. }
  42. appDomain.RegisterCrossBindingAdaptor(adaptor);
  43. }
  44. // 初始化ILRuntime的protobuf
  45. InitializeILRuntimeProtobuf(appDomain);
  46. LitJson.JsonMapper.RegisterILRuntimeCLRRedirection(appDomain);
  47. }
  48. public static void InitializeILRuntimeProtobuf(ILRuntime.Runtime.Enviorment.AppDomain appDomain)
  49. {
  50. ProtoBuf.PType.RegisterFunctionCreateInstance((typeName)=>PType_CreateInstance(appDomain, typeName));
  51. ProtoBuf.PType.RegisterFunctionGetRealType(PType_GetRealType);
  52. }
  53. private static object PType_CreateInstance(ILRuntime.Runtime.Enviorment.AppDomain appDomain, string typeName)
  54. {
  55. return appDomain.Instantiate(typeName);
  56. }
  57. private static Type PType_GetRealType(object o)
  58. {
  59. Type type = o.GetType();
  60. if (type.FullName == "ILRuntime.Runtime.Intepreter.ILTypeInstance")
  61. {
  62. ILTypeInstance ilo = o as ILTypeInstance;
  63. type = ProtoBuf.PType.FindType(ilo.Type.FullName);
  64. }
  65. return type;
  66. }
  67. }
  68. }