Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions src/OpenCvSharp/Fundamentals/MatMemoryManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System;
using System.Buffers;

namespace OpenCvSharp;

/// <summary>
/// A MemoryManager over an OpenCvSharpMat
/// </summary>
/// <remarks>The pointer is assumed to be fully unmanaged, or externally pinned - no attempt will be made to pin this data</remarks>
public sealed unsafe class MatMemoryManager<T> : MemoryManager<T>
where T : unmanaged
{
private readonly Mat wrapped;

/// <summary>
/// Create a new UnmanagedMemoryManager instance at the given pointer and size
/// </summary>
/// <remarks>It is assumed that the span provided is already unmanaged or externally pinned</remarks>
public MatMemoryManager(Mat mat, bool isDataOwner = true)
{
if (!mat.IsContinuous())
{
throw new ArgumentException("mat is not continuous", nameof(mat));
}

wrapped = isDataOwner ? mat : new Mat(mat);
}

/// <inheritdoc />
public override Span<T> GetSpan() => new((void*)wrapped.Data, (int)wrapped.Total());

/// <summary>
/// Provides access to a pointer that represents the data (note: no actual pin occurs)
/// </summary>
public override MemoryHandle Pin(int elementIndex = 0)
{
if (elementIndex < 0 || elementIndex >= wrapped.Total())
{
throw new ArgumentOutOfRangeException(nameof(elementIndex));
}

var dims = wrapped.Dims;
var idxs = new int[dims];
var remainIdx = elementIndex;
for (var dim = dims - 1; dim >= 0; dim--)
{
remainIdx = Math.DivRem(remainIdx, wrapped.Size(dim), out idxs[dim]);
}

return new MemoryHandle((void*)wrapped.Ptr(idxs));
}

/// <summary>
/// Has no effect
/// </summary>
public override void Unpin()
{
}

/// <summary>
/// Releases all resources associated with this object
/// </summary>
protected override void Dispose(bool disposing)
=> wrapped.Dispose();
}
10 changes: 9 additions & 1 deletion src/OpenCvSharp/Modules/core/Mat/Mat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3572,7 +3572,7 @@ public bool GetRectangularArray<T>(out T[,] data)
/// </summary>
/// <param name="data">Primitive or Vec array to be copied</param>
/// <returns>Length of copied bytes</returns>
public bool SetArray<T>(T[] data)
public bool SetArray<T>(params T[] data)
where T : unmanaged
{
CheckArgumentsForConvert<T>(data);
Expand Down Expand Up @@ -4107,5 +4107,13 @@ public void ForEachAsVec6d(MatForeachFunctionVec6d operation)

#endregion

/// <summary>
/// Creates a new span over the Mat.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public unsafe Span<T> AsSpan<T>() where T : unmanaged
=> IsContinuous() ? new Span<T>(DataPointer, (int)Total()) : Span<T>.Empty;

#endregion
}