ILHelper.cs 2.2 KB

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