UPacket.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. Log.Debug("111111111111111111111: " + enetPacket.DataLength);
  72. var bytes = new byte[(long)enetPacket.DataLength];
  73. Marshal.Copy(enetPacket.Data, bytes, 0, (int) enetPacket.DataLength);
  74. return bytes;
  75. }
  76. }
  77. }
  78. }