我刚从 vs2008 切换到 vs2010。完全相同的解决方案,除了现在对 C++ dll 的每次调用都会产生“pinvokestackimbalance”异常。
此异常在 2008 年没有被触发。我可以完全访问 C++ dll 和调用应用程序。 pinvoke似乎没有任何问题,但是这个问题使调试其他问题变得不可能; IDE 经常停下来告诉我这些事情。
例如,这是 C# 签名:
[DllImport("ImageOperations.dll")]
static extern void FasterFunction(
[MarshalAs(UnmanagedType.LPArray)]ushort[] inImage, //IntPtr inImage,
[MarshalAs(UnmanagedType.LPArray)]byte[] outImage, //IntPtr outImage,
int inTotalSize, int inWindow, int inLevel);
这是它在 C++ 端的样子:
#ifdef OPERATIONS_EXPORTS
#define OPERATIONS_API __declspec(dllexport)
#else
#define OPERATIONS_API __declspec(dllimport)
#endif
extern "C" {
OPERATIONS_API void __cdecl FasterFunction(unsigned short* inArray,
unsigned char* outRemappedImage,
int inTotalSize,
int inWindow, int inLevel);
}
vs2010 和 vs2008 之间有什么不同会导致这些异常被抛出?我应该向 DllImport 指令添加一组不同的参数吗?
最佳答案
首先,了解代码是错误的(并且一直是错误的)。 “pInvokeStackImbalance”本身并不是一个异常(exception),而是一个托管调试助手。 VS2008默认关闭,但是很多人没有开启,所以VS2010默认开启。 MDA 不会在 Release 模式下运行,所以如果你为 release 构建它就不会触发。
在您的情况下,调用约定不正确。 DllImport
默认为 CallingConvention.WinApi
,这与 x86 桌面代码的 CallingConvention.StdCall
相同。应该是CallingConvention.Cdecl
。
这可以通过将 [DllImport("ImageOperations.dll")]
行编辑为:
[DllImport("ImageOperations.dll", CallingConvention = CallingConvention.Cdecl)]
有关详细信息,请参阅 this MSDN reference
关于c# - pinvokestackimbalance - 我该如何解决或关闭它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3506796/