Packet.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. if (packet == IntPtr.Zero)
  11. {
  12. throw new InvalidOperationException("No native packet.");
  13. }
  14. this.packet = packet;
  15. }
  16. public Packet(string data, PacketFlags flags = PacketFlags.None)
  17. {
  18. if (data == null)
  19. {
  20. throw new ArgumentNullException("data");
  21. }
  22. this.packet = Native.enet_packet_create(data, (uint)data.Length, flags);
  23. if (this.packet == IntPtr.Zero)
  24. {
  25. throw new ENetException(0, "Packet creation call failed.");
  26. }
  27. }
  28. ~Packet()
  29. {
  30. Dispose(false);
  31. }
  32. public void Dispose()
  33. {
  34. Dispose(true);
  35. GC.SuppressFinalize(this);
  36. }
  37. private void Dispose(bool disposing)
  38. {
  39. if (this.packet == IntPtr.Zero)
  40. {
  41. return;
  42. }
  43. Native.enet_packet_destroy(this.packet);
  44. this.packet = IntPtr.Zero;
  45. }
  46. public ENetPacket Struct
  47. {
  48. get
  49. {
  50. return (ENetPacket)Marshal.PtrToStructure(this.packet, typeof(ENetPacket));
  51. }
  52. set
  53. {
  54. Marshal.StructureToPtr(value, this.packet, false);
  55. }
  56. }
  57. public IntPtr NativePtr
  58. {
  59. get
  60. {
  61. return this.packet;
  62. }
  63. }
  64. }
  65. }