title: How to pass managed Bitmap from C# to wrapped unmanaged OpenCV's Mat
body: <p>I have a project with 3 parts:</p>
  
  <ol>
  <li><p>Managed C# project with a callback which gives me a Bitmap (it should have PixelFormat = Format24bppRgb). I've tried several ways to convert the Bitmap into something I could pass to part 2, that's the last thing I've tried:</p>
  
  <pre><code>public int BufferCB(IntPtr pBuffer, int BufferLen)
  {
      byte[] aux = new byte[BufferLen];
      Marshal.Copy(pBuffer, aux, 0, BufferLen);
      String s_aux = System.Text.Encoding.Default.GetString(aux);
      wrappedClassInstance.GetBitmap(s_aux);
  }
  </code></pre></li>
  <li><p>Managed C++/CLI to wrap item 3:</p>
  
  <pre><code>int WrappedClass::GetBitmap(array&lt;System::Byte&gt;^ s_in) {
      pin_ptr&lt;unsigned char&gt; pin = &amp;s_in[0];
      unsigned char* p = pin;
      return privateImplementation-&gt;GetBitmap(p);
  }
  </code></pre></li>
  <li><p>Unmanaged C++ application that uses OpenCV. I want to load this data into a Mat with:</p>
  
  <pre><code>Mat myMat;
  int NativeClass::GetBitmap(unsigned char *s_in) {
  
      // If there's no input:
      if (!s_in) {
          return -1;
      }
      /* h and w are defined elsewhere */
      myMat = Mat(h, w, CV_8UC3, (void *)s_in, Mat::AUTO_STEP));
      imwrite("test.bmp", myMat);
      return 0;
  }
  </code></pre></li>
  </ol>
  
  <p>When the the imwrite function is reached an exception is thrown: "System.Runtime.InteropServices.SEHException (0x80004005)". It doesn't say much, but I'm guessing the data I passed into the Mat got corrupted when I've  marshalled it.</p>
  
  <p>Before, I was trying to pass the data without a wrapper:</p>
  
  <pre><code>[DllImport("mydll.dll", ...)]
  static extern void GetBitmap(IntPtr pBuffer, int h, int w);
  
  void TestMethod(IntPtr pBuffer, int BufferLen)
  {
      // h and w defined elsewhere
      // GetBitmap is essentially the same as in item 3.
      GetBitmap(pBuffer, BufferLen, h, w);
  }
  </code></pre>
  
  <p>and that worked (it saved the Bitmap into the file), but because the DLL stays attached until I kill the process that solution is not good enough for me. I also don't want to "mirror" the Mat class into my project, as I know Mat should accept data from some char*. </p>
  
  <p>Please help, how can I do this? Am I doing wrong type conversions?</p>
  
  <p>Thank you.</p>