首先,我要感谢所有花时间阅读本文的人!我是一位消息灵通的 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 项目的相应发布/调试目录中。我可以在调试/发布模式下单击顶部的“开始”按钮,WPF 窗体将打开并显示该按钮。我可以单击该按钮,然后从 DLL 函数中看到正确的返回代码,一切运行正常。但是,当我将发布文件夹复制到任何其他计算机上以在那里运行它时,我的 WPF 表单仅在单击按钮(并调用我的 DLL 函数)时打开,我的程序崩溃并显示:
“testdll.exe 中 0x7c812fd3 处出现未处理的异常:0xE0434352:0xe0434352。”
我可以使用 Visual Studio 2005 在 C# 中创建类似的 GUI。我进行相同的 DLL 调用并利用相同的 C# 代码和设置。我在其他计算机上打开此应用程序没有任何问题,并且 DLL 函数被正确调用,没有错误。这似乎是我仅在 VS2012 中遇到的问题。请注意,我在出现故障的计算机上安装了 .NET Framework 4 和 C++ 2012 Redistributable 软件包。在互联网上搜索类似的结果并修改了许多项目设置后,我仍然感到困惑。任何帮助将不胜感激。