ProtobufHelper.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Google.Protobuf;
  2. using System;
  3. using System.ComponentModel;
  4. using System.IO;
  5. namespace KYFramework.Network
  6. {
  7. public static class ProtobufHelper
  8. {
  9. public static byte[] ToBytes(object message)
  10. {
  11. return ((Google.Protobuf.IMessage)message).ToByteArray();
  12. }
  13. public static void ToStream(object message, MemoryStream stream)
  14. {
  15. ((Google.Protobuf.IMessage)message).WriteTo(stream);
  16. }
  17. public static object FromBytes(Type type, byte[] bytes, int index, int count)
  18. {
  19. object message = Activator.CreateInstance(type);
  20. ((Google.Protobuf.IMessage)message).MergeFrom(bytes, index, count);
  21. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  22. if (iSupportInitialize == null)
  23. {
  24. return message;
  25. }
  26. iSupportInitialize.EndInit();
  27. return message;
  28. }
  29. public static object FromBytes(object instance, byte[] bytes, int index, int count)
  30. {
  31. object message = instance;
  32. ((Google.Protobuf.IMessage)message).MergeFrom(bytes, index, count);
  33. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  34. if (iSupportInitialize == null)
  35. {
  36. return message;
  37. }
  38. iSupportInitialize.EndInit();
  39. return message;
  40. }
  41. public static object FromStream(Type type, MemoryStream stream)
  42. {
  43. object message = Activator.CreateInstance(type);
  44. ((Google.Protobuf.IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
  45. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  46. if (iSupportInitialize == null)
  47. {
  48. return message;
  49. }
  50. iSupportInitialize.EndInit();
  51. return message;
  52. }
  53. public static object FromStream(object message, MemoryStream stream)
  54. {
  55. // 这个message可以从池中获取,减少gc
  56. ((Google.Protobuf.IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
  57. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  58. if (iSupportInitialize == null)
  59. {
  60. return message;
  61. }
  62. iSupportInitialize.EndInit();
  63. return message;
  64. }
  65. }
  66. }