title: Accessing c++ dll library from c#
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/3506796/pinvokestackimbalance-how-can-i-fix-this-or-turn-it-off">pinvokestackimbalance — how can I fix this or turn it off?</a>  </p>
  </blockquote>
  
  
  
  <p>I need to access a c++ dll library (I don't have the source code) from c# code.</p>
  
  <p>for example the following functions:</p>
  
  <pre><code>UINT32 myfunc1()
  UINT32 myfunc2(IN char * var1)
  UINT32 myfunc3(IN char * var1, OUT UINT32 * var2)
  </code></pre>
  
  <p>For myfunc1 I have no problems when I use the following code:</p>
  
  <pre><code>[DllImport("mydll.dll")]
  public static extern int myfunc1();
  </code></pre>
  
  <p>On the other hand I was unable to use myfunc2 and myfunc3.
  For myfunc2 I tried the following: (and many others desperately)</p>
  
  <pre><code>[DllImport("mydll.dll")]
  public static extern int myfunc2(string var1);
  
  [DllImport("mydll.dll")]
  public static extern int myfunc2([MarshalAs(UnmanagedType.LPStr)] string var1);
  
  [DllImport("mydll.dll")]
  public static extern int myfunc2(char[] var1);
  </code></pre>
  
  <p>But all of them gave the following error:
  <code>"Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\....\myproject\bin\Debug\myproj.vshost.exe'.</code></p>
  
  <p>Additional Information: A call to PInvoke function <code>'myproject!myproject.mydll::myfunc2'</code> has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature."</p>
  
  <p>Please, guide on what I should do.</p>