Packet.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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(string data, PacketFlags flags = PacketFlags.None)
  13. {
  14. if (data == null)
  15. {
  16. throw new ArgumentNullException("data");
  17. }
  18. this.packet = Native.enet_packet_create(data, (uint)data.Length, flags);
  19. if (this.packet == IntPtr.Zero)
  20. {
  21. throw new ENetException(0, "Packet creation call failed.");
  22. }
  23. }
  24. ~Packet()
  25. {
  26. Dispose(false);
  27. }
  28. public void Dispose()
  29. {
  30. 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. Native.enet_packet_destroy(this.packet);
  40. this.packet = IntPtr.Zero;
  41. }
  42. public 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 NativePtr
  54. {
  55. get
  56. {
  57. return this.packet;
  58. }
  59. }
  60. public uint Length
  61. {
  62. get
  63. {
  64. if (this.packet == IntPtr.Zero)
  65. {
  66. return 0;
  67. }
  68. return this.Struct.dataLength;
  69. }
  70. }
  71. public string Data
  72. {
  73. get
  74. {
  75. if (this.packet == IntPtr.Zero)
  76. {
  77. return "";
  78. }
  79. ENetPacket pkt = this.Struct;
  80. if (pkt.data == IntPtr.Zero)
  81. {
  82. return "";
  83. }
  84. return Marshal.PtrToStringAuto(pkt.data, (int)pkt.dataLength);
  85. }
  86. }
  87. }
  88. }