在C++中生成的dll,函数定义为int CebxInitial(string inFilename)
在WPF中调用(属于C#吧),编译链接没错,运行报错:
Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'E:\WPFtestCebxTools\WPFtestCebxTools\bin\Debug\WPFtestCebxTools.vshost.exe'.
Additional Information: A call to PInvoke function 'WPFtestCebxTools!WPFtestCebxTools.MainWindow::CebxInitial' 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.
是不是说类型不匹配啊?我试了试,除非传空参数不报错,传string、char*都报错,就是运行到
res  = CebxInitial(namein);///////////////
这一行时报错。
是我的DllImport时参数设置不对还是其他的啊?WPF中大致代码如下:
namespace WPFtestCebxTools
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
            ///////////////////////////
        [DllImport("CebxtoPngDll.dll", EntryPoint = "CebxInitial",
        CharSet = CharSet.Ansi,
        CallingConvention = CallingConvention.StdCall)]
        public static extern Int32  CebxInitial(String inFilename);        public MainWindow()
        {
            InitializeComponent();            //StringBuilder namein = new StringBuilder("D:\\test.cebx");
            string namein = "D:\\test.cebx";
            //StringBuilder nameout = new StringBuilder("D:\\test.png");
            String nameout = "D:\\test.png";
            String exfcnameout = "no exfc";            Int32 res = 0;            res  = CebxInitial(namein);///////////////
        }
     }
}

解决方案 »

  1.   

    c++里面要用int CebxInitial(LPCWSTR inFilename)
    因为c#不能理解c++的string(std::string)之所以出现'PInvokeStackImbalance'异常,是因为std::string大小为32个字节,而C#的string或char*作为指针,只有4个(x86)或8个(x64)字节。
      

  2.   

    c++的string,是特殊类型,这么干不行啊,改一下c++代码吧
      

  3.   

    谢谢,那如果C++里用LPCWSTR 型,在C#里调用时该用什么类型呢
      

  4.   

    c++里面改成int CebxInitial(LPCWSTR inFilename)了,C#里没动,还是String,还是报错啊
      

  5.   

    C++按楼上的改成了LPCWSTR 型参数,C#里没变,还是有错误啊,会不会我的代码放错位置了,或者少了什么引用的内容,或者哪些参数设置有问题啊
      

  6.   

    改成:int CebxInitial(char* inFilename);
    这样最简单!
      

  7.   

    谢谢大家的回答,我找身边的高手给看了看,已经解决了在C++里定义函数时加个__sdkcall,即:
    int __stdcall CebxInitial(LPCTSTR inFilename);
    然后自己在内部匹配一下类型就可以了,LPCTSTR 应该也可以换成其他类型,但是关键问题还是VS2005里的C和VS2010里的wpf对于堆栈的处理方式不一样,所以这样设置一下就好了