不平衡堆栈!

我写了一个VC ++ DLL。 dll中某个方法的声明如下:

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

我在使用P / Invoke的C#代码中使用此dll。 我将声明作为:

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

我将代码中的函数调用为:

 startIt(0); 

现在,当遇到这一行时,编译器会抛出这个错误:

 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. 

我无法理解为什么它会抛出此错误,因为托管代码和非托管代码中的签名都是相同的。 而且,在我的另一台机器上,相同的代码在visual studio中运行得很好。 所以,这让我觉得抛出的错误是误导。

请帮忙。

谢谢

当您调用外部函数时,使用的调用约定默认为__stdcall 。 由于您的函数使用__cdecl约定,因此您需要将其声明为:

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

你能错过你的DllImport属性中的CallingConvention=CallingConvention.Cdecl吗?

康斯坦丁和弗雷德里克哈米迪已正确回答了这个问题,如何解决这个问题。 这有助于避免最终的堆栈溢出。 我自己多次咬过这个。 这里真正起作用的是,.NET 4启用了一个托管调试助手,用于在32位x86计算机(非64位)上进行调试(而不是发布),以检查错误指定的p / invoke调用。 这篇MSDN文章详细介绍了这一点: http : //msdn.microsoft.com/en-us/library/0htdy0k3.aspx 。 Stephen Cleary在这篇文章中发现了这一点值得称赞 : pinvokestackimbalance – 如何修复此问题或将其关闭?