ArrayAddress.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.Runtime.InteropServices;
  2. #pragma warning disable 1591
  3. // ReSharper disable InconsistentNaming
  4. namespace OpenCvSharp.Internal.Util;
  5. /// <summary>
  6. ///
  7. /// </summary>
  8. /// <typeparam name="T"></typeparam>
  9. public class ArrayAddress1<T> : DisposableObject
  10. where T : unmanaged
  11. {
  12. private readonly Array array;
  13. private GCHandle gch;
  14. public ArrayAddress1(T[] array)
  15. {
  16. this.array = array ?? throw new ArgumentNullException(nameof(array));
  17. gch = GCHandle.Alloc(array, GCHandleType.Pinned);
  18. }
  19. public ArrayAddress1(IEnumerable<T> enumerable)
  20. : this(enumerable.ToArray())
  21. {
  22. }
  23. public ArrayAddress1(T[,] array)
  24. {
  25. this.array = array ?? throw new ArgumentNullException(nameof(array));
  26. gch = GCHandle.Alloc(array, GCHandleType.Pinned);
  27. }
  28. /// <summary>
  29. /// Releases unmanaged resources
  30. /// </summary>
  31. protected override void DisposeUnmanaged()
  32. {
  33. if (gch.IsAllocated)
  34. {
  35. gch.Free();
  36. }
  37. base.DisposeUnmanaged();
  38. }
  39. public IntPtr Pointer => gch.AddrOfPinnedObject();
  40. public int Length => array.Length;
  41. }