为什么我得到" PInvokeStackImbalance检测"对于这个简单的例子吗?例子、简单、QUOT、PInvokeStackImbalance

2023-09-03 12:01:12 作者:我想跟你鬼混

我创建了一个非常简单的PInvoke示例:

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);

但每当我打电话上述 NativeMethods.Add 方法,我得到以下托管调试助手:

But whenever I call the above NativeMethods.Add method I get the following managed debug assistant:

PInvokeStackImbalance检测   消息:!CommonManagedLib CommonManagedLib.NativeMethods ::添加A调用PInvoke的功能有不平衡的堆栈。这可能是因为管理的PInvoke签名也非托管的目标签名不匹配。检查调用约定和的PInvoke签名的参数匹配目标非托管签名。

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.

然后呼叫与预期的返回值完成,但具有MDA消息出现既讨厌,令人担忧的 - 我不完全理解的PInvoke呢,但是从我读过,我pretty的肯定我的签名是正确的 - 什么?我做错了

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?

这是所有在32位操作系统。

This is all on a 32-bit OS.

推荐答案

您需要,而不是使用的或者的

You need to instead use either

[DllImport("CommonNativeLib.dll", CallingConvention = CallingConvention.Cdecl)]

extern "C" __declspec(dllexport) __stdcall int Add(int a, int b) ...

由于常规的C函数的工作方式不同于Windows API函数;他们的调用约定是不同的,这意味着它们是如何绕过的参数是不同的。 (这是暗示在错误。)

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.)