UPacket.cs 1.5 KB

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