ProtobufHelper.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.ComponentModel;
  3. using System.IO;
  4. using Google.Protobuf;
  5. namespace ETModel
  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 object FromBytes(Type type, byte[] bytes, int index, int count)
  14. {
  15. object message = Activator.CreateInstance(type);
  16. ((Google.Protobuf.IMessage)message).MergeFrom(bytes, index, count);
  17. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  18. if (iSupportInitialize == null)
  19. {
  20. return message;
  21. }
  22. iSupportInitialize.EndInit();
  23. return message;
  24. }
  25. public static object FromStream(Type type, MemoryStream stream)
  26. {
  27. object message = Activator.CreateInstance(type);
  28. ((Google.Protobuf.IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
  29. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  30. if (iSupportInitialize == null)
  31. {
  32. return message;
  33. }
  34. iSupportInitialize.EndInit();
  35. return message;
  36. }
  37. public static object FromStream(object message, MemoryStream stream)
  38. {
  39. // 这个message可以从池中获取,减少gc
  40. ((Google.Protobuf.IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
  41. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  42. if (iSupportInitialize == null)
  43. {
  44. return message;
  45. }
  46. iSupportInitialize.EndInit();
  47. return message;
  48. }
  49. }
  50. }