开发者社区> 问答> 正文

C#中调用C++生成的dll出错,请教请教!? 400 报错

C#中调用C++生成的dll出错,请教请教!? 400 报错

在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);///////////////
        }
     }
}

展开
收起
爱吃鱼的程序员 2020-06-02 11:59:00 738 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    楼上的我试了下,还是有问题,不过谢谢你的回答,我找身边的高手给看了看,已经解决了

    在C++里定义函数时加个 __sdkcall,即:
    int __stdcall CebxInitial(LPCTSTR inFilename);
    然后自己在内部匹配一下类型就可以了,

    LPCTSTR 应该也可以换成其他类型,但是关键问题还是VS2005里的C和VS2010里的wpf对于

    堆栈的处理方式不一样,所以这样设置一下就好了######

    public static extern Int32  CebxInitial(
    [MarshalAs(UnmanagedType.LPStr)]
    String inFilename
    );

    ######汗...C++默认都是__cdecl,不改变成__stdcall,声明的时候 CallingConvention.StdCall当然要出错.另外既然C++的dll有源码Debug很容易就能发现问题所在了.######

    感觉不对吧.不同语言间交互,这个最好用COM吧,方便而且通用.

    ######__cdecl,__stdcall 两者的堆栈清理者是不同的
    2020-06-02 11:59:20
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载