Unbalanced Stack!

I wrote a VC ++ dll. The declaration for one of the methods in the dll is as follows:

extern "C" _declspec(dllexport) void startIt(int number) { capture = cvCaptureFromCAM(number); } 

I use this dll in C # code using P / Invoke. I am making the announcement as follows:

 [DllImport("Tracking.dll", EntryPoint = "startIt")] public extern static void startIt(int number); 

and I call the function in code like:

 startIt(0); 

Now that this line is encountered, the compiler throws me this error:

 A call to PInvoke function 'UsingTracking!UsingTracking.Form1::startIt' 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. 

I cannot understand why this throws this error, since the signature in the managed and unmanaged code is the same. Moreover, on my other machine, the same code works fine in a visual studio. Thus, it makes me think that the error that the error throws is wrong.

Please, help.

thanks

+7
c # dll visual-c ++ pinvoke
source share
3 answers

When you p / call an external function, the calling convention is used by default __stdcall . Since your function uses the __cdecl , you need to declare it as such:

 [DllImport("Tracking.dll", EntryPoint = "startIt", CallingConvention = CallingConvention.Cdecl)] public extern static void startIt(int number); 
+13
source share

Can't you lose CallingConvention=CallingConvention.Cdecl in your DllImport attribute?

+6
source share

Konstantin and Frederick Hamidi correctly answered this question, how to solve this problem. This can help avoid the possible. I have already bitten myself several times. What is really in the game is that .NET 4 included a managed debugging assistant for debugging (not release) on 32-bit x86 machines (not 64-bit), which checks for an incorrectly specified p / invoke call. This MSDN article states the following: http://msdn.microsoft.com/en-us/library/0htdy0k3.aspx . Stephen Cleary deserves recognition for this: pinvokestackimbalance - how can I fix or disable this?

+4
source share

All Articles