为什么我会收到“检测到 PInvokeStackImbalance”对于这个简单的例子?
我正在创建一个非常简单的 PInvoke 示例:
extern "C" __declspec(dllexport) int Add(int a, int b)
{
return a + b;
}
[DllImport("CommonNativeLib.dll")]
extern public static int Add(int a, int b);
return NativeMethods.Add(a, b);
但是每当我调用上面的 NativeMethods.Add
方法时,我都会得到以下托管调试助手:
检测到 PInvokeStackImbalance 消息:对 PInvoke 函数“CommonManagedLib!CommonManagedLib.NativeMethods::Add”的调用使堆栈不平衡。这可能是因为托管 PInvoke 签名与非托管目标签名不匹配。检查 PInvoke 签名的调用约定和参数是否与目标非托管签名匹配。
然后调用以预期的返回值完成,但是出现 MDA 消息既烦人又令人担忧 - 我还没有完全理解 PInvoke,但从我读到的内容来看,我很确定我的签名是正确的 - 什么我做错了吗?
这一切都在 32 位操作系统上进行。
I'm creating a very simple PInvoke sample:
extern "C" __declspec(dllexport) int Add(int a, int b)
{
return a + b;
}
[DllImport("CommonNativeLib.dll")]
extern public static int Add(int a, int b);
return NativeMethods.Add(a, b);
But whenever I call the above NativeMethods.Add
method I get the following managed debug assistant:
PInvokeStackImbalance was detected
Message: A call to PInvoke function 'CommonManagedLib!CommonManagedLib.NativeMethods::Add' 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.
The call then completes with the expected return value, but having the MDA message appear is both annoying and worrying - I don't fully understand PInvoke yet, but from what I've read I'm pretty sure that my signature is correct - what am I doing wrong?
This is all on a 32-bit OS.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用 任一
或,
因为常规 C 函数的工作方式与 Windows API 函数不同;它们的“调用约定”不同,这意味着它们传递参数的方式不同。 (错误中已经暗示了这一点。)
You need to instead use either
or
because regular C functions work differently than the Windows API functions; their "calling conventions" are different, meaning how they pass around parameters is different. (This was hinted at in the error.)
堆栈不平衡的原因要么是签名不匹配,要么是调用约定默认调用约定是 stdcall。当您的调用约定是 stdcall 时,如果您希望调用者使用 cdecl 调用约定清理堆栈,则被调用者会清理堆栈。您可以在 此处找到更多信息
但如果您因为签名而面临问题,只需访问上面的链接即可
使用 PInvoke 扩展解决基于签名的堆栈不平衡问题
The Stack Imbalance reasons are either the signature is not matching else Calling Convention by default calling convention is stdcall. When your calling convention is stdcall callee cleans the stack if you want caller to clean the stack us cdecl calling convention. you can find more Here
But if you are facing because of signature, just go through above link
Solve Signature based Stack Imbalance issues using PInvoke extension