c# - pinvokestackimbalance - 我该如何解决或关闭它?

标签 c# c++ visual-studio-2010 visual-studio pinvoke

我刚从 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/

相关文章:

c# - 为什么我的 C# 应用程序无法加载我的 C++ dll?

c# - 匹配进程参数的正则表达式

c++ - 为什么复制和 move 构造函数一起调用?

c++ - 使用 C++ 和 OpenCV 从蒙版和输入图像创建透明 PNG 图像

centos 上的 c++ automake 预编译 header 支持

visual-studio-2010 - 从PE或PDB文件中获取调试信息

c# - 是否可以对内联 SQL 进行语法高亮显示?

c# - fluent nhibernate - 同一实体上的多对多关系映射

c# - 使用 json.net 列表到 json 对象

visual-studio-2010 - 升级到 Visual Studio 2010 的一些主要原因是什么? (同时使用 .NET 3.5)