ProtobufHelper.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. // 这个message可以从池中获取,减少gc
  16. object message = Activator.CreateInstance(type);
  17. ((Google.Protobuf.IMessage)message).MergeFrom(bytes, index, count);
  18. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  19. if (iSupportInitialize == null)
  20. {
  21. return message;
  22. }
  23. iSupportInitialize.EndInit();
  24. return message;
  25. }
  26. public static object FromStream(Type type, MemoryStream stream)
  27. {
  28. // 这个message可以从池中获取,减少gc
  29. object message = Activator.CreateInstance(type);
  30. ((Google.Protobuf.IMessage)message).MergeFrom(stream.GetBuffer(), (int)stream.Position, (int)stream.Length);
  31. ISupportInitialize iSupportInitialize = message as ISupportInitialize;
  32. if (iSupportInitialize == null)
  33. {
  34. return message;
  35. }
  36. iSupportInitialize.EndInit();
  37. return message;
  38. }
  39. }
  40. }