c#中调用c/C++的dll时,需要加上CallingConvention特性参数,否则容易出现PInvokeStackImbalance异常。例如,以下问题描述及解决 方式。
(一)问题描述
在利用C#调用本地dll库时,原先在c/c++中的函数原型如下:
extern "C" __declspec(dllexport) int playSpecificSound(wchar_t* fileName);
在c#中原先这样声明:
[DllImport("ASR\\ASR.dll", EntryPoint = "playSpecificSound")]
public static extern int PlaySpecificSound(IntPtr fileNameWithAbsoultePath);
在C#中的调用方式为:
PlaySpecificSound(Encoding.Unicode.GetBytes(Encoding.Unicode.GetBytes(fileName)));
问题出现:在调用过程中,总是出现PInvokeStackImbalance的异常。原本以为是x64系统导致的,但未能解决。
(二)问题解决
当C#中修改为如下的声明时(加上CallingConvention = CallingConvention.Cdecl),一切正常,问题解决。
[DllImport("ASR\\ASR.dll", EntryPoint = "playSpecificSound", CallingConvention = CallingConvention.Cdecl)]
public static extern int PlaySpecificSound(IntPtr fileNameWithAbsoultePath);