PInvokeStackImbalance C# call to unmanaged C++ function

前端 未结 5 1787
礼貌的吻别
礼貌的吻别 2020-12-05 00:09

After switching to VS2010, the managed debug assistant is displaying an error about an unbalanced stack from a call to an unmanaged C++ function from a C# application.

<
相关标签:
5条回答
  • 2020-12-05 00:30

    It's good.I update function define as follow:

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

    It works well.

    0 讨论(0)
  • 2020-12-05 00:33

    As mentioned in Dane Rose's comment, you can either use __stdcall on your C++ function or declare CallingConvention = CallingConvention.Cdecl on your DllImport.

    0 讨论(0)
  • 2020-12-05 00:36

    You specify no padding in your C# declaration of the struct, but not in the C++ version. Since you are mixing char arrays that are not all multiples of four and an odd number of 2 byte shorts, the compiler is probably inserting padding within the struct and add the end.

    Try wrapping the struct in a #pragma pack to ensure no padding.

    #pragma pack(push)
    #pragma pack(1)
    
    // The struct
    
    #pragma pack(pop)
    
    0 讨论(0)
  • 2020-12-05 00:36

    Had the same problem as described - unmanaged C++ app that has worked perfectly for years. When we upgraded to VS2010, we started getting PInvokeStackUnbalanced messages.

    adding "__stdcall" to the C++ signature as described above made the issue go away.

    0 讨论(0)
  • 2020-12-05 00:37

    You specify stdcall in C# but not in C++, a mismatch here will lead to both the function and the caller popping arguments off of the stack.

    On the other hand there is a compiler switch that will turn on stdcall as the default calling convention, (-Gz) are you using that?

    Or try this in your C++

    short __stdcall SuperSpecialOpenFileFunc(SuperSpecialStruct * stuff);
    
    0 讨论(0)
提交回复
热议问题