Packet.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*******************************************************************************
  2. Copyright © 2015-2022 PICO Technology Co., Ltd.All rights reserved.
  3. NOTICE:All information contained herein is, and remains the property of
  4. PICO Technology Co., Ltd. The intellectual and technical concepts
  5. contained herein are proprietary to PICO Technology Co., Ltd. and may be
  6. covered by patents, patents in process, and are protected by trade secret or
  7. copyright law. Dissemination of this information or reproduction of this
  8. material is strictly forbidden unless prior written permission is obtained from
  9. PICO Technology Co., Ltd.
  10. *******************************************************************************/
  11. namespace Pico.Platform.Models
  12. {
  13. using System;
  14. using System.Runtime.InteropServices;
  15. /// <summary>
  16. /// The information about the message packet.
  17. /// </summary>
  18. public sealed class Packet : IDisposable
  19. {
  20. /// The size of the message packet.
  21. private readonly ulong size;
  22. /// The handler of the message packet.
  23. private readonly IntPtr handler;
  24. public Packet(IntPtr handler)
  25. {
  26. this.handler = handler;
  27. this.size = (ulong) CLIB.ppf_Packet_GetSize(handler);
  28. }
  29. /// <summary>Get message content.</summary>
  30. public ulong GetBytes(byte[] dest)
  31. {
  32. if ((ulong) dest.LongLength >= size)
  33. {
  34. Marshal.Copy(CLIB.ppf_Packet_GetBytes(handler), dest, 0, (int) size);
  35. return size;
  36. }
  37. else
  38. {
  39. throw new ArgumentException($"Dest array can't hold {size} bytes");
  40. }
  41. }
  42. /// <summary>Get message content.</summary>
  43. public string GetBytes()
  44. {
  45. if (size > 0)
  46. {
  47. byte[] bytes = new byte[size];
  48. Marshal.Copy(CLIB.ppf_Packet_GetBytes(handler), bytes, 0, (int) size);
  49. return System.Text.Encoding.UTF8.GetString(bytes);
  50. }
  51. else
  52. {
  53. return string.Empty;
  54. }
  55. }
  56. /// <summary>Get the ID of the message sender.</summary>
  57. public string SenderId
  58. {
  59. get { return CLIB.ppf_Packet_GetSenderID(handler); }
  60. }
  61. /// <summary>Get message size.</summary>
  62. public ulong Size
  63. {
  64. get { return size; }
  65. }
  66. #region IDisposable
  67. ~Packet()
  68. {
  69. Dispose();
  70. }
  71. public void Dispose()
  72. {
  73. CLIB.ppf_Packet_Free(handler);
  74. GC.SuppressFinalize(this);
  75. }
  76. #endregion
  77. }
  78. }
粤ICP备19079148号