ScopedGCHandle.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System.Runtime.InteropServices;
  2. #pragma warning disable 1591
  3. namespace OpenCvSharp.Internal.Util;
  4. /// <summary>
  5. /// Original GCHandle that implement IDisposable
  6. /// </summary>
  7. // ReSharper disable once InconsistentNaming
  8. public sealed class ScopedGCHandle : IDisposable
  9. {
  10. private GCHandle handle;
  11. private bool disposed;
  12. /// <summary>
  13. /// Constructor
  14. /// </summary>
  15. /// <param name="value"></param>
  16. public ScopedGCHandle(object value)
  17. {
  18. if (value is null)
  19. throw new ArgumentNullException(nameof(value));
  20. handle = GCHandle.Alloc(value);
  21. disposed = false;
  22. }
  23. /// <summary>
  24. /// Constructor
  25. /// </summary>
  26. /// <param name="value"></param>
  27. /// <param name="type"></param>
  28. public ScopedGCHandle(object value, GCHandleType type)
  29. {
  30. if (value is null)
  31. throw new ArgumentNullException(nameof(value));
  32. handle = GCHandle.Alloc(value, type);
  33. disposed = false;
  34. }
  35. /// <summary>
  36. /// Constructor
  37. /// </summary>
  38. /// <param name="handle"></param>
  39. private ScopedGCHandle(GCHandle handle)
  40. {
  41. this.handle = handle;
  42. disposed = false;
  43. }
  44. public void Dispose()
  45. {
  46. if (!disposed)
  47. {
  48. // Release managed resources.
  49. if (handle.IsAllocated)
  50. {
  51. handle.Free();
  52. }
  53. disposed = true;
  54. }
  55. }
  56. public static ScopedGCHandle FromIntPtr(IntPtr value)
  57. {
  58. return new ScopedGCHandle(GCHandle.FromIntPtr(value));
  59. }
  60. public static IntPtr ToIntPtr(ScopedGCHandle value)
  61. {
  62. if (value is null)
  63. throw new ArgumentNullException(nameof(value));
  64. return GCHandle.ToIntPtr(value.Handle);
  65. }
  66. public GCHandle Handle => handle;
  67. public bool IsAllocated => handle.IsAllocated;
  68. public object? Target => handle.Target;
  69. public void Free()
  70. {
  71. handle.Free();
  72. }
  73. public override string? ToString()
  74. {
  75. return handle.ToString();
  76. }
  77. }