c#调用C/C++代码时出现的PInvokeStackImbalance异常实例及解决方式

来源:互联网 发布:怎么拿到网站数据库 编辑:程序博客网 时间:2024/05/20 07:35

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


原创粉丝点击