6

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.

Community
  • 1
  • 1
fonurr
  • 75
  • 2
  • 8
  • have you tried to disable the vshost in project settings? – VladL Jan 07 '13 at 10:21
  • 2
    Take a look at [pinvokestackimbalance — how can I fix this or turn it off?](http://stackoverflow.com/questions/3506796/pinvokestackimbalance-how-can-i-fix-this-or-turn-it-off) – Ken Kin Jan 07 '13 at 10:23
  • I think this post will help you, http://stackoverflow.com/questions/14152192/build-native-c-for-use-as-net-library/14152267 – Pranit P Kothari Jan 07 '13 at 11:06
  • I think this post will help you, http://coolthingoftheday.blogspot.in/2008/03/pinvoke-tool-you-been-looking-for-all.html – Pranit P Kothari Jan 07 '13 at 11:10

2 Answers2

5

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);
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

It might just be a character set mismatch try this

[DllImport("mydll.dll", CharSet = CharSet.Ansi)]
public static extern int SendText([MarshalAs(UnmanagedType.LPStr)] string var1);

Nicked from:

DLL import char * pointer from C#

Community
  • 1
  • 1
Rich
  • 331
  • 2
  • 7