title: C# PInvoke pass reference to int[]
body: <p>I'm trying to pass an int[8] reference to a C++ DLL, but a <code>System.ExecutionEngineException</code> is thrown in C# when it returns. Here is the C++ code:</p>
  
  <pre><code>extern "C" __declspec(dllexport) int __stdcall ReadFlashCfg(int* flData);
  int __stdcall ReadFlashCfg(int* flData)
  {
      return mctl.ReadFlashCfg(flData);
  }// breakpoint here shows flData is correct
  </code></pre>
  
  <p>And the C# DLL wrapper code:</p>
  
  <pre><code>[DllImport(MyDllPath)]
  private static extern int ReadFlashCfg(ref int[] fData);
  
  public static int[] ReadFlashCfgNoRc()
  {
     var flData = new int[8];
     var rc = ReadFlashCfg(ref flData); //Exception happens here
     if (rc != 0) throw new Exception(rc.ToString());
     return flData;
  }
  </code></pre>
  
  <p>And the C# calling code:</p>
  
  <pre><code>var fd = ReadFlashCfgNoRc();
  </code></pre>
  
  <p>A breakpoint on the very last line of the C++ code shows the array populated with correct data. </p>
  
  <p>The exception happens upon returning from <code>ReadFlashCfg(ref flData)</code> in the DLL wrapper.</p>
  
  <p>I think I need to let the C++ know the size of the array (it's always 8) so that it can manage the stack correctly.</p>
  
  <p>I know I can pass eight individual int*, but there has to be simpler way - is there?</p>