Access C ++ dll library from C #

Possible duplicate:
pinvokestackimbalance - how can I fix or disable this?

I need to access the C ++ dll library (I don't have 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 problem when I use the following code:

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

On the other hand, I was not able 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 they all gave the following error: "Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\....\myproject\bin\Debug\myproj.vshost.exe'.

Additional information: the call to the PInvoke function 'myproject!myproject.mydll::myfunc2' has an unbalanced stack. This is likely due to the fact that the PInvoke managed signature does not match the unmanaged target signature. Verify that the calling agreement and PInvoke signature settings match the target unmanaged signature.

Please explain what I should do.

+6
source share
2 answers

Your C ++ functions use the cdecl calling cdecl , but the default DllImport for DllImport is stdcall . This conditional call mismatch is the most common cause of an MDA error with an unbalanced stack.

You fix the issue by matching call conventions. The easiest way to do this is to modify the C # code to specify cdecl as follows:

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

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

Blocked by:

DLL import char * pointer from C #

0
source

All Articles