在 WPF 中,使用 C++ 编写的 DLL 文件

WPF运行在CLR上的,它的代码是托管代码。

C++编写的DLL代码是非托管的。

在WPF中调用C++编写的DLL代码需要使用: 

 

[csharp] view plaincopy
 
  1. using System.Runtime.InteropServices;  
  2.    
  3.  [DllImport("Dll.dll", EntryPoint = "add",CallingConvention=CallingConvention.Cdecl)]  
  4.  public static extern int add(int a, int b);  



 

 

下面详细说明之。

编译生成DLL文件

在Visual Studio 2010中,File --> New --> Project --> Visual C++ --> Win32 --> Win32 Project

比如我们为工程起名为Dll,在弹出的对话框中,选择DLL,点击Finish即可。

 

在Dll.cpp中添加代码

 

[cpp] view plaincopy
 
  1. #include "stdafx.h"  
  2.    
  3. int add(int a,int b)  
  4. {  
  5.          returna+b;         
  6. }  

 

 

 

为了导出时不发生名字改编,我们添加一个模块定义文件Dll.def,方法是右击工程名àAddàNew Item,在弹出的对话框中,选择Module-Difinition File(.def),文件名为Dll.def。

在Dll.def中添加代码

 

 

[cpp] view plaincopy
 
  1. LIBRARY Dll.dll  
  2. EXPORTS  
  3. add  



 

 

Build工程即可。在Debug目录下,会有Dll.dll文件生成。

 

【注】关于C++ DLL 这一部分,可以参考我的前期博文。

 

在WPF中使用DLL

新建一个WPF工程。

将Dll.dll文件拷贝到WPF工程的Debug目录下。

 

 

[csharp] view plaincopy
 
  1. //一些其他的命名空间  
  2. using System.Runtime.InteropServices;  
  3.    
  4. namespace Wpf  
  5. {  
  6.     /// <summary>  
  7.     /// Interaction logic for MainWindow.xaml  
  8.     /// </summary>  
  9.     public partial class MainWindow : Window  
  10.     {  
  11.         [DllImport("Dll.dll", EntryPoint = "add",CallingConvention=CallingConvention.Cdecl)]  
  12.         public static extern int add(int a, int b);  
  13.    
  14.         public MainWindow()  
  15.         {  
  16.             InitializeComponent();  
  17.             inta = MainWindow.add(12,12);  
  18.             MessageBox.Show(a.ToString());  
  19.         }  
  20.     }  
  21. }  



 

注意事项

1.      Dll.dll一定要拷贝到WPF工程的Debug目录下

2.      一定要注意堆栈的调用约定

Visual C++ 代码的默认调用约定是C调用约定(__cdecl)

而不是标准调用约定(__stdcall)或Pascal调用约定(__pascal)

所以在DllImport中,CallingConvention参数一定要设置成CallingConvention.Cdecl。

 

当然,我们也可以通过修改Dll.dll的调用约定,如

 

[cpp] view plaincopy
 
  1. int WINAPI  add(int a,int b)  

 

将add函数的调用约定设置为WINAPI,也就是标准调用约定,

这样,在WPF中引入时,DllImport的CallingConvention参数就可以省略不写,因为默认是标准调用约定

 

[csharp] view plaincopy
 
  1. [DllImport("Dll.dll", EntryPoint = "add"]  
posted @   卡萨丁·周  阅读(675)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示