title: Passing struct to unmanaged DLL with PInvoke
body: <p>due to several restrictions related to the project and not this problem in particular, I'm trying to pass through PInvoke a struct containing the data relevant to the Mat constructor of a Bitmap on C#.<br>
  In C# I receive a Bitmap, called frame, and in order to access the pixel data I'm doing:</p>
  
  <pre><code>BitmapData data = frame.LockBits(new Rectangle(0,0,frame.Width,frame.Height), ImageLockMode.ReadWrite, frame.PixelFormat);
  </code></pre>
  
  <p>using <code>data.Scan0</code> as the <code>IntPtr</code> I create the struct for my unmanaged dll. Obviously, after calling my external function, I call <code>frame.UnlockBits(data);</code></p>
  
  <p>Here is the code<br>
  <strong>C# Invoke</strong></p>
  
  <pre><code>[DllImport("ImageProcessingExtern", CallingConvention = CallingConvention.Cdecl)]
  public static extern void drawLine(IntPtr objPtr, ref ExportBitmap bitmap);
  </code></pre>
  
  <p><strong>C# Struct declaration</strong></p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential, Pack=8)]
  public struct ExportBitmap
  {
      public int height;
      public int width;
      public IntPtr data;
      public int step;
      public int channels;
  }
  </code></pre>
  
  <p><strong>C++ function declaration</strong></p>
  
  <pre><code>CVAPI(void) drawLine(ObjectsFinder* objPtr, ExportBitmap* bitmap) {
      cv::Mat testmat(cv::Size(bitmap-&gt;width, bitmap-&gt;height), CV_MAKETYPE(CV_8U, bitmap-&gt;channels), bitmap-&gt;data, bitmap-&gt;step);
  }
  </code></pre>
  
  <p><strong>C++ Struct</strong></p>
  
  <pre><code>#pragma pack(push, 8)
  typedef struct ExportBitmap
  {
      int height;
      int width;
      void* data;
      int step;
      int channels;
  } ExportBitmap;
  #pragma pack(pop)
  </code></pre>
  
  <p>So far my code seems to work as long as I don't create that mat. If I modify ANY parameter other than the data inside the IntPtr everything works fine. When using the Mat constructor line I get an error saying the DLL is not a valid Win32 application(error code 193 from kernel32 LoadLibrary())</p>
  
  <p>I've been stuck for about two weeks searching for a solution to this and I'm still not sure what is going on, I can only think there is a problem with how I'm obtaining the editable bitmap data, but I'm not sure what the problem with it might be.</p>