gpt4 book ai didi

c# - 在 WPF 应用程序中加载非托管 DLL

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:24 26 4
gpt4 key购买 nike

我知道我的问题可能看起来重复了。但是请相信我,我已经尝试了这个网站上提出的几个答案,但到目前为止都没有成功。因此,如果有人能告诉我我在做什么有什么问题,我将不胜感激。我以及其他刚开始处理 DLL 和 WPF 的人(我已经尝试过 thisthisthis )将非常感谢一份清晰的分步指南。

这是最简单形式的 C++ 代码:

#include <stdio.h>
#pragma unmanaged

extern "C"
{
__declspec(dllexport) int add(int a,int b)
{
return a+b;
}
__declspec(dllexport) int subtract(int a,int b)
{
return a-b;
}
}

好的,所以我将其放入 Visual C++ 2013 的 DLL 项目中并构建它。这是成功的,并给我一个名为 OurDLL.dll 的文件。

现在,我创建一个新的 C# WPF 应用程序,尽可能编写最简单的方法并将以下行添加到文件 MainWindow.xaml.cs:

/// some using statements

using System.Runtime.InteropServices;
namespace test1
{
public partial class MainWindow : Window
{
[DllImport("OurDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int add(int a, int b);

/// the rest of the code

代码成功编译和构建。我已将 DLL 文件放入文件夹 test1\bin\Debug。但是每当我尝试使用 add 函数时,都会出现一个异常窗口,告诉我:

An unhandled exception of type 'System.BadImageFormatException' occurred in test1.exe

Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

现在我真的很沮丧,不知道该怎么办:(

最佳答案

问题很可能是 C++ 和 C# 应用程序的build设置不一致。

尝试检查this , thisthis答案。希望这会有所帮助。

关于c# - 在 WPF 应用程序中加载非托管 DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36953834/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com