开发者

PInvokeStackBalance keeps being detected while the signature is OK

开发者 https://www.devze.com 2023-02-06 04:57 出处:网络
I have a little problem with my code. I\'ve got a unmanaged C++ .dll that I want to use with a C# applaction.

I have a little problem with my code. I've got a unmanaged C++ .dll that I want to use with a C# applaction.

The C++ function in the dll looks like this:

void EXPORT_API vSetLights(BYTE byLights)
{
    remote.SetLEDs(byLights);
}

The C# code looks like this:

    [DllImport("APlugin")]
    private static extern void vSetLights(byte byLights);

And I call the function like this:

        byte byLeds = 0x0;
        vSetLights(byLeds);

If I'm correct, the function signature is ok (Both return nothing and require a byte), but the PInvokeStackBalance keeps popping up. The application runs just fine 开发者_StackOverflow社区after that, can I safely ifnore it or is there a fix?

Thanks,

Wesley


Your stack imbalance is probably caused by a difference in calling convention. The default calling convention in DllImport is WinApi (which in turn defaults to StdCall). It's likely that your C++ function is using the Cdecl calling convention. You'll have to show us the definition of EXPORT_API in order to be sure.

The stack imbalance occurs because StdCall expects the called function to clean up the stack, and Cdecl expects the caller to clean up the stack. So if a program that expects StdCall calls a Cdecl function, the stack doesn't get cleaned up. Going the other way (Cdecl calling StdCall), the stack gets cleaned up twice.

You can change your DllImport to use Cdecl, like this:

[DllImport("APlugin", CallingConvention=CallingConvention.Cdecl)]

0

精彩评论

暂无评论...
验证码 换一张
取 消