如何从C#Windows应用程序项目中调用C ++ dll [英] how to call a C++ dll from C# windows application project

查看:177
本文介绍了如何从C#Windows应用程序项目中调用C ++ dll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Visual Studio中的类库项目在C ++中创建了一个dll。我需要从C#应用程序调用dll中的方法。

I have created a dll in C++ using a Class Library project in Visual Studio. I need to call a method in the dll from a C# application.

我知道有2个方法。一种是将dll项目引用添加到C#项目或使用DllExport导出方法。但是,当我以两种方式尝试时,在运行时调用dll方法时,总是会出现以下错误。

I got to know there are 2 approches. One is to add the dll project reference to C# project or use DllExport to export method. However when I tried in both ways it always gives the following error when the dll method is called in runtime.

类型为'System.BadImageFormatException'的未处理异常TestClient.exe
中发生了其他信息:试图加载格式不正确的程序。 (来自HRESULT的异常:0x8007000B)

我知道如何避免此问题吗?

Can i know how to avoid this problem ?

推荐答案

此错误意味着您正在尝试将32位DLL加载到64位进程中或将64位DLL转换为32位进程。在Windows上,DLL的位数必须与进程的位数匹配才能正确加载。

This error means that you're trying to load a 32-bit DLL into a 64-bit process or a 64-bit DLL into a 32-bit process. On Windows, the bitness of the DLL must match the bitness of the process in order for it to load correctly.

您的本机DLL是32位还是64位?在您的C#项目构建设置中,您要定位的平台是什么?如果进入C#项目属性,则可以转到构建选项卡,然后将平台目标更改为x86或x64之类的特定内容,以匹配为您的本机DLL构建的平台。

Is your native DLL 32- or 64-bit? In your C# project build settings, what platform are you targeting? If you go into the C# project properties, you can go to the Build tab and change the "Platform target" to something specific like x86 or x64 to match the platform that your native DLL was built for.

另一种选择是构建本机DLL以匹配您的C#应用​​程序的平台。如果C#应用程序的平台是AnyCPU,则它将在32位Windows上以32位运行,在64位Windows上以64位运行。因此,您将需要本机DLL的32位和64位版本。

The other alternative would be to build the native DLL to match the platform of your C# application. If the C# application's platform is AnyCPU, though, it will run as 32-bit on 32-bit Windows and 64-bit on 64-bit Windows. Because of this, you would need both a 32- and 64-bit version of your native DLL.

我建议将C#应用程序的平台设置为特定的平台(x86, x64),然后更改本地DLL的平台以匹配。

I would recommend setting your C# application's platform to something specific (x86, x64) and then change your native DLL's platform to match.

这篇关于如何从C#Windows应用程序项目中调用C ++ dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆