DlibDotNet icon indicating copy to clipboard operation
DlibDotNet copied to clipboard

Accessing data of the Array2D via IntPtr?

Open antongit opened this issue 5 years ago • 4 comments

Hello @takuya-takeuchi,

I'm just wondering if it's possible to directly access the data of Array2D via the pointer and size (or even Memory<T>)? Without going through the ToBytes (which probably makes another copy)?

Thank you!

Best, Anton

antongit avatar May 15 '19 17:05 antongit

Do you want to copy Array2D data to managed array you declared? I will provide

Array2D<T>.Size
Array2D<T>.CopyTo(T[])

Does it satisfy your hope?

takuya-takeuchi avatar May 15 '19 22:05 takuya-takeuchi

Without going through the ToBytes...

Trying to access NativePtr field of DlibObject in unsafe context?

  unsafe {
       int nativePtr = 0xBADC0DE; // consider value from NativePtr
       IntPtr ptr = (IntPtr)(void*)(nativePtr);  // NativePtr  
    }

// Be ready to burn your time in debugger sessions!

valerysntx avatar May 16 '19 20:05 valerysntx

NativePtr is internal. I guess he wants to get head of pointer like OpenCVSharp.Mat.Data.

takuya-takeuchi avatar May 16 '19 22:05 takuya-takeuchi

NativePtr is internal

Approach of direct memory access via pointers math still exists in Array2D<T> class, so implementing IMemoryOwner for Array2D<T> class is possible without much effort... E.g.:

public class Buffer2D<T> : Array2DBase<T>  
    where T : struct
{
    private MemorySource<T> memorySource;
    public Buffer2D(MemorySource<T> memorySource, int width, int height)
    {
        this.memorySource = memorySource;
        this.Width = width;
        this.Height = height;
    }

    public int Width { get; private set; }

    public int Height { get; private set; }

    /// <summary>
    /// Gets the backing <see cref="MemorySource{T}"/>
    /// </summary>
    public MemorySource<T> MemorySource => this.memorySource;

    public Memory<T> Memory => this.MemorySource.Memory;

    public Span<T> Span => this.Memory.Span;

    public ref T this[int x, int y]
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get
        {

            Span<T> span = this.Span;
            return ref span[(this.Width * y) + x];
        }
    }

The idea is to use internal NativePtr value of Array2D in Buffer2D class, by setting up IMemorySource pointing to that address.

valerysntx avatar May 17 '19 01:05 valerysntx