WPF runs on the CLR, and its code is managed code.
The DLL code written in C ++ is not hosted.
To call the DLL code written in C ++ in WPF, use:
using System.Runtime.InteropServices; [DllImport("Dll.dll", EntryPoint = "add",CallingConvention=CallingConvention.Cdecl)] public static extern int add(int a, int b);
The following is a detailed description.
Compile and generate DLL files
In Visual Studio 2010, File --> New --> Project --> Visual C ++ --> Win32 --> Win32 Project
For example, we name the project Dll. In the displayed dialog box, select DLL and click Finish.
Add code to Dll. cpp
#include "stdafx.h" int add(int a,int b){ returna+b; }
To avoid name adaptation during export, we add a module definition file Dll. def, right-click the project name, and select Module-Difinition File (. def), the file name is Dll. def.
Add code to Dll. def
LIBRARY Dll.dllEXPORTSadd
Build the project. The Dll. dll file is generated under the Debug directory.
[Note] for C ++ DLL, refer to my previous blog.
Use DLL in WPF
Create a new WPF project.
Copy the Dll. dll file to the Debug directory of the WPF project.
// Some other namespaces 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 (. toString ());}}}
Notes
1. Dll. dll must be copied to the Debug directory of the WPF project.
2. Pay attention to the stack call conventions.
The default call Convention for Visual C ++ code is the C call Convention (_ cdecl)
Instead of standard call conventions (_ stdcall) or Pascal call conventions (_ pascal)
Therefore, in DllImport, The CallingConvention parameter must be set to CallingConvention. Cdecl.
Of course, we can also modify the Dll. dll call conventions, as shown in figure
int WINAPI add(int a,int b)
Set the call convention of the add function to WINAPI, that is, the standard call convention,
In this way, the CallingConvention parameter of DllImport can be omitted and not written when it is introduced in WPF, because it is a standard call Convention by default.
[DllImport("Dll.dll", EntryPoint = "add"]