OVRNativeBuffer.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Runtime.InteropServices;
  3. public class OVRNativeBuffer : IDisposable
  4. {
  5. public OVRNativeBuffer(int numBytes)
  6. {
  7. this.Reallocate(numBytes);
  8. }
  9. ~OVRNativeBuffer()
  10. {
  11. this.Dispose(false);
  12. }
  13. public void Reset(int numBytes)
  14. {
  15. this.Reallocate(numBytes);
  16. }
  17. public int GetCapacity()
  18. {
  19. return this.m_numBytes;
  20. }
  21. public IntPtr GetPointer(int byteOffset = 0)
  22. {
  23. if (byteOffset < 0 || byteOffset >= this.m_numBytes)
  24. {
  25. return IntPtr.Zero;
  26. }
  27. return (byteOffset != 0) ? new IntPtr(this.m_ptr.ToInt64() + (long)byteOffset) : this.m_ptr;
  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.disposed)
  37. {
  38. return;
  39. }
  40. if (disposing)
  41. {
  42. }
  43. this.Release();
  44. this.disposed = true;
  45. }
  46. private void Reallocate(int numBytes)
  47. {
  48. this.Release();
  49. if (numBytes > 0)
  50. {
  51. this.m_ptr = Marshal.AllocHGlobal(numBytes);
  52. this.m_numBytes = numBytes;
  53. }
  54. else
  55. {
  56. this.m_ptr = IntPtr.Zero;
  57. this.m_numBytes = 0;
  58. }
  59. }
  60. private void Release()
  61. {
  62. if (this.m_ptr != IntPtr.Zero)
  63. {
  64. Marshal.FreeHGlobal(this.m_ptr);
  65. this.m_ptr = IntPtr.Zero;
  66. this.m_numBytes = 0;
  67. }
  68. }
  69. private bool disposed;
  70. private int m_numBytes;
  71. private IntPtr m_ptr = IntPtr.Zero;
  72. }