title: Getting distorted images after sending them from C# to OpenCV in C++?
body: <p>I created a C DLL out of my C++ class which uses <code>OpenCV</code> for image manipulations and want to use this DLL in my C# application. Currently, this is how I have implemented it:</p>
  
  <pre><code>#ifdef CDLL2_EXPORTS
  #define CDLL2_API __declspec(dllexport)
  #else
  #define CDLL2_API __declspec(dllimport)
  #endif
  
  #include "../classification.h" 
  extern "C"
  {
      CDLL2_API void Classify_image(unsigned char* img_pointer, unsigned int height, unsigned int width, char* out_result, int* length_of_out_result, int top_n_results = 2);
      //...
  }
  </code></pre>
  
  <p>C# related code:</p>
  
  <p>DLL Import section:</p>
  
  <pre><code>//Dll import 
  [DllImport(@"CDll2.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
  static extern void Classify_Image(IntPtr img, uint height, uint width, byte[] out_result, out int out_result_length, int top_n_results = 2);
  </code></pre>
  
  <p>The actual function sending the image to the DLL:  </p>
  
  <pre><code>//...
  //main code 
  private string Classify(int top_n)
  {
      byte[] res = new byte[200];
      int len;
      Bitmap img = new Bitmap(txtImagePath.Text);
      BitmapData bmpData = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), 
                                        ImageLockMode.ReadWrite,  
                                        PixelFormat.Format24bppRgb);
      Classify_Image(bmpData.Scan0, (uint)bmpData.Height, (uint)bmpData.Width, res, out len, top_n);
      img.UnlockBits(bmpData); //Remember to unlock!!!
      //...
  }
  </code></pre>
  
  <p>and the C++ code in the DLL : </p>
  
  <pre><code>CDLL2_API void Classify_Image(unsigned char* img_pointer, unsigned int height, unsigned int width,
                                char* out_result, int* length_of_out_result, int top_n_results)
      {
          auto classifier = reinterpret_cast&lt;Classifier*&gt;(GetHandle());
  
          cv::Mat img = cv::Mat(height, width, CV_8UC3, (void*)img_pointer, Mat::AUTO_STEP);
  
          std::vector&lt;Prediction&gt; result = classifier-&gt;Classify(img, top_n_results);
  
          //...
          *length_of_out_result = ss.str().length();
      }
  </code></pre>
  
  <p>This works perfectly with some images but it doesn't work with others, for example when I try to <code>imshow</code> the image in the <code>Classify_Image</code>, right after being created from the data sent by C# application, I am faced with images like this :</p>
  
  <p>Problematic example:   </p>
  
  <p><a href="https://i.stack.imgur.com/JwuVb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JwuVb.jpg" alt="enter image description here"></a></p>
  
  <p>Fine example:</p>
  
  <p><a href="https://i.stack.imgur.com/xmng1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xmng1.jpg" alt="enter image description here"></a></p>