Search code examples
c#c++pinvoke

Accessing c++ dll library from c#


Possible Duplicate:
pinvokestackimbalance — how can I fix this or turn it off?

I need to access a c++ dll library (I don't have the source code) from c# code.

for example the following functions:

UINT32 myfunc1()
UINT32 myfunc2(IN char * var1)
UINT32 myfunc3(IN char * var1, OUT UINT32 * var2)

For myfunc1 I have no problems when I use the following code:

[DllImport("mydll.dll")]
public static extern int myfunc1();

On the other hand I was unable to use myfunc2 and myfunc3. For myfunc2 I tried the following: (and many others desperately)

[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);

But all of them gave the following error: "Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\....\myproject\bin\Debug\myproj.vshost.exe'.

Additional Information: A call to PInvoke function 'myproject!myproject.mydll::myfunc2' 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."

Please, guide on what I should do.


Solution

  • Your C++ functions use the cdecl calling convention, but the default calling convention for DllImport is stdcall. This calling convention mismatch is the most common cause of the stack imbalanced MDA error.

    You fix the problem by making the calling conventions match. The easiest way to do that is to change the C# code to specify cdecl like this:

    [DllImport("mydll.dll", CallingConvention=CallingConvention.Cdecl)]
    public static extern int myfunc2(string var1);