PInvokeStackImbalance C#调用非托管C函数

切换到VS2010后,受管调试助手正在从C#应用程序对非托管C函数的调用显示有关不平衡堆栈的错误。

通常的嫌疑犯似乎并没有造成这个问题。还有什么我应该检查? VS2008内置的C dll和C#应用从来没有问题,没有奇怪或神秘的bug – 是的,我知道这并不意味着什么。

这里是检查的事情:

> dll名称是正确的。
>入口点名称是正确的,并已使用depends.exe验证 – 代码必须使用该名称。
>调用约定是正确的。
>尺寸和类型都似乎是正确的。
>字符集正确。
>在忽略错误后似乎没有任何问题,并且在调试器外部运行时没有问题。

C#:

[DllImport("Correct.dll", EntryPoint = "SuperSpecialOpenFileFunc", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern short SuperSpecialOpenFileFunc(ref SuperSpecialStruct stuff);

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct SuperSpecialStruct
{
   public int field1;
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
   public string field2;
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
   public string field3;
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
   public string field4;
   public ushort field5;
   public ushort field6;
   public ushort field7;
   public short field8;
   public short field9;
   public uint field10;
   public short field11;
};

C :

short SuperSpecialOpenFileFunc(SuperSpecialStruct * stuff);

struct SuperSpecialStruct
{
   int               field1;
   char              field2[256];
   char              field3[20];
   char              field4[10];
   unsigned short    field5;
   unsigned short    field6;
   unsigned short    field7;
   short             field8;
   short             field9;
   unsigned int      field10;
   short             field11;
};

这里是错误:

Managed Debugging Assistant
‘PInvokeStackImbalance’ has detected a
problem in ‘Managed application path’.

Additional Information: A call to
PInvoke function
‘SuperSpecialOpenFileFunc’ 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.

Dane Rose’s comment中所提到的,你可以在你的C函数上使用__stdcall或在你的DllImport上声明CallingConvention = CallingConvention.Cdecl。

这是解决我的问题的答案。

http://stackoverflow.com/questions/2390407/pinvokestackimbalance-c-sharp-call-to-unmanaged-c-function

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:PInvokeStackImbalance C#调用非托管C函数