title: How to copy correctly data from Open CV Mat to SafeHandle
body: <p>I got legacy code. Somtimes I get <code>AccessViolationException</code> in <code>Memory.Copy</code>.
  I think, I have problem in <code>array.DangerousGetHandle()</code>.
  How to copy correctly and should I do it?</p>
  <pre><code>private static void CopyData(Mat mat, RasterImage image)
  {
      int stride = (int) mat.Step();
      int dataSize = stride * mat.Height;
      
      image.Data.CopyFrom(mat.Data);
  }
  
  public static void CopyFrom(this UnmanagedArray array, IntPtr src)
  {
      Memory.Copy(src, array.DangerousGetHandle(), array.Size);
  }
  
  public static class Memory
  {
      public static void Copy(IntPtr src, IntPtr dst, int count)
      {
          unsafe
          {
              Buffer.MemoryCopy(src.ToPointer(), dst.ToPointer(), count, count);
          }
      }
  }
  
  public class UnmanagedArray : SafeHandleZeroOrMinusOneIsInvalid // SafeBuffer
  {
      private static readonly GcInstanceCounter InstanceCounter = new GcInstanceCounter();
  
      public int Size { get; }
  
      public UnmanagedArray(int size)
          : base(true)
      {
          if (size &lt;= 0) throw new ArgumentOutOfRangeException(nameof(size));
          Size = size;
  
          InstanceCounter.Increment(Size);
  
          SetHandle(Marshal.AllocHGlobal(Size));
          GC.AddMemoryPressure(Size);
      }
  
      protected override bool ReleaseHandle()
      {
          InstanceCounter.Decrement(Size);
  
          Marshal.FreeHGlobal(handle);
          GC.RemoveMemoryPressure(Size);
          return true;
      }
  }
  </code></pre>
  <p>I think add new constructor to UnmanagedArray class</p>
  <pre><code>public UnmanagedArray(IntPtr handle) : base(true)
  {
      SetHandle(handle);
  }
  </code></pre>
  <p>and</p>
  <pre><code>image.Data = new UnmanagedArray(mat.Data);
  </code></pre>
  <p>But I'm not sure</p>
  <p>Update 1.
  I did copy data from Mat:</p>
  <pre><code>mat.GetArray(out byte[] arr);
  </code></pre>
  <p>then Marshal.Copy</p>
  <pre><code>image.Data.CopyFrom(arr);
  
  public static void CopyFrom(this UnmanagedArray array, byte[] src)
  {
       Marshal.Copy(src, 0, array.DangerousGetHandle(), array.Size);
  }
  </code></pre>
  <p>It fixed the problem. But I have double copy now.
  I think, the problem is that the mat is destroyed.</p>
  <p>Benchmark for (1920 * 5) x (1080 * 5)</p>
  <p><a href="https://i.stack.imgur.com/cjT5T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cjT5T.png" alt="enter image description here" /></a></p>