ProtobufHelper.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.ComponentModel;
  3. using System.IO;
  4. using ProtoBuf.Meta;
  5. namespace ET
  6. {
  7. public static class ProtobufHelper
  8. {
  9. public static void Init()
  10. {
  11. }
  12. public static object FromBytes(Type type, byte[] bytes, int index, int count)
  13. {
  14. using (MemoryStream stream = new MemoryStream(bytes, index, count))
  15. {
  16. object o = RuntimeTypeModel.Default.Deserialize(stream, null, type);
  17. if (o is ISupportInitialize supportInitialize)
  18. {
  19. supportInitialize.EndInit();
  20. }
  21. return o;
  22. }
  23. }
  24. public static byte[] ToBytes(object message)
  25. {
  26. using (MemoryStream stream = new MemoryStream())
  27. {
  28. ProtoBuf.Serializer.Serialize(stream, message);
  29. return stream.ToArray();
  30. }
  31. }
  32. public static void ToStream(object message, MemoryStream stream)
  33. {
  34. ProtoBuf.Serializer.Serialize(stream, message);
  35. }
  36. public static object FromStream(Type type, MemoryStream stream)
  37. {
  38. object o = RuntimeTypeModel.Default.Deserialize(stream, null, type);
  39. if (o is ISupportInitialize supportInitialize)
  40. {
  41. supportInitialize.EndInit();
  42. }
  43. return o;
  44. }
  45. }
  46. }