无法从WPF应用程序加载非托管C ++ DLL

时间:2013-02-22 22:50:42

标签: wpf dllimport unmanaged dllexport

首先,我要感谢所有阅读此内容的人!我是一个非常了解C#的WinForms程序员,我给了WPF一个机会。我一直无法从我的WPF应用程序调用函数,所以我决定创建一个非常简单的示例项目来说明我的问题。在这个应用程序中,我正在创建一个C ++ Dll(使用Visual Studio 2012 - > Visual C ++ - > Win32控制台应用程序 - > .DLL项目)。在这个DLL中,我只是创建一个函数来返回一个DWORD。我的DLL如下所示:

// mydll.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
extern "C" __declspec(dllexport) DWORD __cdecl init();

DWORD __cdecl init()
{
    return 0x1234;
}

现在我还有一个WPF应用程序(使用VS 2012),其中我只是尝试从上述DLL调用并打印函数的结果。我的WPF代码在表单中创建了一个按钮。单击按钮后,我调用我的DLL函数并打开一个MessageBox以从函数返回值,简单如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
namespace testdll
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        [DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern uint init();

        public unsafe MainWindow()
        {
            InitializeComponent();

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            uint ret = init();
            MessageBox.Show("Return = " + ret.ToString());
        }
    }
}

在我的项目设置中,我正在“不安全”下编译,也适用于x86平台目标。我能够编译这两个项目,并将DLL项目的构建输出设置为我的WPF项目的相应Release / Debug目录。我可以在Debug / Release模式下点击顶部的“Start”按钮,打开WPF表单并显示按钮。我可以单击按钮,我从DLL的功能中看到正确的返回代码,一切正常。但是,当我将release文件夹复制到任何其他机器上以在那里运行它时,我的WPF表单只在单击按钮(并调用我的DLL函数)时打开,我的程序崩溃:

“testdll.exe中0x7c812fd3处的未处理异常:0xE0434352:0xe0434352。”

我可以使用Visual Studio 2005在C#中创建类似的GUI。我正在进行相同的DLL调用并使用相同的C#代码和设置。我在其他计算机上打开此应用程序没有问题,并且DLL函数被正确调用,没有错误。这似乎是我只有VS2012的问题。请注意,我在计算机上安装了.NET Framework 4和C ++ 2012 Redistributable软件包。在互联网上搜索类似的结果,以及许多项目设置,我仍然难倒。任何帮助都会非常感激。

0 个答案:

没有答案
相关问题