MatMemoryManager.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System.Buffers;
  2. namespace OpenCvSharp;
  3. /// <summary>
  4. /// A MemoryManager over an OpenCvSharpMat
  5. /// </summary>
  6. /// <remarks>The pointer is assumed to be fully unmanaged, or externally pinned - no attempt will be made to pin this data</remarks>
  7. public sealed unsafe class MatMemoryManager<T> : MemoryManager<T>
  8. where T : unmanaged
  9. {
  10. private readonly Mat wrapped;
  11. /// <summary>
  12. /// Create a new UnmanagedMemoryManager instance at the given pointer and size
  13. /// </summary>
  14. /// <remarks>It is assumed that the span provided is already unmanaged or externally pinned</remarks>
  15. public MatMemoryManager(Mat mat, bool isDataOwner = true)
  16. {
  17. if (mat is null)
  18. throw new ArgumentNullException(nameof(mat));
  19. if (!mat.IsContinuous())
  20. throw new ArgumentException("mat is not continuous", nameof(mat));
  21. wrapped = isDataOwner ? mat : new Mat(mat);
  22. }
  23. /// <inheritdoc />
  24. public override Span<T> GetSpan() => new((void*)wrapped.Data, (int)wrapped.Total());
  25. /// <summary>
  26. /// Provides access to a pointer that represents the data (note: no actual pin occurs)
  27. /// </summary>
  28. public override MemoryHandle Pin(int elementIndex = 0)
  29. {
  30. if (elementIndex < 0 || elementIndex >= wrapped.Total())
  31. throw new ArgumentOutOfRangeException(nameof(elementIndex));
  32. var dims = wrapped.Dims;
  33. var idxs = new int[dims];
  34. var remainIdx = elementIndex;
  35. for (var dim = dims - 1; dim >= 0; dim--)
  36. {
  37. remainIdx = Math.DivRem(remainIdx, wrapped.Size(dim), out idxs[dim]);
  38. }
  39. return new MemoryHandle((void*)wrapped.Ptr(idxs));
  40. }
  41. /// <summary>
  42. /// Has no effect
  43. /// </summary>
  44. public override void Unpin()
  45. {
  46. }
  47. /// <summary>
  48. /// Releases all resources associated with this object
  49. /// </summary>
  50. protected override void Dispose(bool disposing)
  51. => wrapped.Dispose();
  52. }