Packet.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace ENet
  4. {
  5. public sealed class Packet: IDisposable
  6. {
  7. private IntPtr packet;
  8. public Packet(IntPtr packet)
  9. {
  10. this.packet = packet;
  11. }
  12. public Packet(byte[] data, PacketFlags flags = PacketFlags.None)
  13. {
  14. if (data == null)
  15. {
  16. throw new ArgumentNullException("data");
  17. }
  18. this.packet = NativeMethods.enet_packet_create(data, (uint) data.Length, flags);
  19. if (this.packet == IntPtr.Zero)
  20. {
  21. throw new ENetException("Packet creation call failed");
  22. }
  23. }
  24. ~Packet()
  25. {
  26. this.Dispose(false);
  27. }
  28. public void Dispose()
  29. {
  30. this.Dispose(true);
  31. GC.SuppressFinalize(this);
  32. }
  33. private void Dispose(bool disposing)
  34. {
  35. if (this.packet == IntPtr.Zero)
  36. {
  37. return;
  38. }
  39. NativeMethods.enet_packet_destroy(this.packet);
  40. this.packet = IntPtr.Zero;
  41. }
  42. private ENetPacket Struct
  43. {
  44. get
  45. {
  46. return (ENetPacket) Marshal.PtrToStructure(this.packet, typeof (ENetPacket));
  47. }
  48. set
  49. {
  50. Marshal.StructureToPtr(value, this.packet, false);
  51. }
  52. }
  53. public IntPtr PacketPtr
  54. {
  55. get
  56. {
  57. return this.packet;
  58. }
  59. set
  60. {
  61. this.packet = value;
  62. }
  63. }
  64. public uint Length
  65. {
  66. get
  67. {
  68. if (this.packet == IntPtr.Zero)
  69. {
  70. return 0;
  71. }
  72. return this.Struct.dataLength;
  73. }
  74. }
  75. public byte[] Bytes
  76. {
  77. get
  78. {
  79. var enetPacket = this.Struct;
  80. var bytes = new byte[enetPacket.dataLength];
  81. Marshal.Copy(enetPacket.data, bytes, 0, (int) enetPacket.dataLength);
  82. return bytes;
  83. }
  84. }
  85. }
  86. }