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

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

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

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

using System.Runtime.InteropServices;


[DllImport("Dll.dll", EntryPoint = "add",CallingConvention=CallingConvention.Cdecl)]

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中添加代码

#include "stdafx.h"


int add(int a,int b)

{

returna+b;

}

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

在Dll.def中添加代码

LIBRARY Dll.dll

EXPORTS

add

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

 

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

 

在WPF中使用DLL

新建一个WPF工程。

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

//一些其他的命名空间

using System.Runtime.InteropServices;


namespace Wpf

{

/// <summary>

/// Interaction logic for MainWindow.xaml

/// </summary>

public partial class MainWindow : Window

{

[DllImport("Dll.dll", EntryPoint = "add",CallingConvention=CallingConvention.Cdecl)]

public static extern int add(int a, int b);


public MainWindow()

{

InitializeComponent();

inta = MainWindow.add(12,12);

MessageBox.Show(a.ToString());

}

}

}

 

注意事项

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

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

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

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

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

 

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

int WINAPI  add(int a,int b)

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

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

[DllImport("Dll.dll", EntryPoint = "add"]

原文链接:https://blog.csdn.net/jarvischu/article/details/6634185

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值