2

首先,我要感谢任何阅读本文的人的时间!我是一个消息灵通的 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 目录。我可以在调试/发布模式下点击顶部的“开始”按钮,然后 WPF 表单打开并显示该按钮。我可以单击该按钮,然后从我的 DLL 函数中看到正确的返回代码,一切正常。但是,当我将发布文件夹复制到任何其他机器上运行它时,我的 WPF 表单仅在单击按钮(并调用我的 DLL 函数)时打开,我的程序崩溃并出现:

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

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

4

0 回答 0