Packet.cs 1.5 KB

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