UPacket.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using Common.Network;
  4. namespace UNet
  5. {
  6. internal sealed class UPacket: IDisposable
  7. {
  8. private IntPtr packet;
  9. public UPacket(IntPtr packet)
  10. {
  11. this.packet = packet;
  12. }
  13. public UPacket(byte[] data, PacketFlags flags = PacketFlags.None)
  14. {
  15. if (data == null)
  16. {
  17. throw new ArgumentNullException("data");
  18. }
  19. this.packet = NativeMethods.ENetPacketCreate(data, (uint) data.Length, flags);
  20. if (this.packet == IntPtr.Zero)
  21. {
  22. throw new UException("Packet creation call failed");
  23. }
  24. }
  25. ~UPacket()
  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.ENetPacketDestroy(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 PacketPtr
  55. {
  56. get
  57. {
  58. return this.packet;
  59. }
  60. set
  61. {
  62. this.packet = value;
  63. }
  64. }
  65. public byte[] Bytes
  66. {
  67. get
  68. {
  69. ENetPacket enetPacket = this.Struct;
  70. var bytes = new byte[(long) enetPacket.DataLength];
  71. Marshal.Copy(enetPacket.Data, bytes, 0, (int) enetPacket.DataLength);
  72. return bytes;
  73. }
  74. }
  75. }
  76. }