ILHelper.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. }
  44. public static void InitializeILRuntimeProtobuf(ILRuntime.Runtime.Enviorment.AppDomain appDomain)
  45. {
  46. ProtoBuf.PType.RegisterFunctionCreateInstance((typeName)=>PType_CreateInstance(appDomain, typeName));
  47. ProtoBuf.PType.RegisterFunctionGetRealType(PType_GetRealType);
  48. }
  49. private static object PType_CreateInstance(ILRuntime.Runtime.Enviorment.AppDomain appDomain, string typeName)
  50. {
  51. return appDomain.Instantiate(typeName);
  52. }
  53. private static Type PType_GetRealType(object o)
  54. {
  55. Type type = o.GetType();
  56. if (type.FullName == "ILRuntime.Runtime.Intepreter.ILTypeInstance")
  57. {
  58. ILTypeInstance ilo = o as ILTypeInstance;
  59. type = ProtoBuf.PType.FindType(ilo.Type.FullName);
  60. }
  61. return type;
  62. }
  63. }
  64. }