ProtobufHelper.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 FromBytes(object instance, byte[] bytes, int index, int count)
  26. {
  27. object message = instance;
  28. ((Google.Protobuf.IMessage)message).MergeFrom(bytes, index, count);
  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(Type type, MemoryStream stream)
  38. {
  39. object message = Activator.CreateInstance(type);
  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. public static object FromStream(object message, MemoryStream stream)
  50. {
  51. // 这个message可以从池中获取,减少gc
  52. ((Google.Protobuf.IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
  53. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  54. if (iSupportInitialize == null)
  55. {
  56. return message;
  57. }
  58. iSupportInitialize.EndInit();
  59. return message;
  60. }
  61. }
  62. }