WPF is widely used, and the Development user interface is indeed very convenient. Sometimes it is necessary to call a lot of DLL libraries previously written in C ++, which involves how to call the DLL compiled in C ++ in C sharp. After some attempts, we found that the call was actually relatively simple. The procedure is as follows:
1: In this example, the DLL name is Test. dll. The provided interface function is also very simple: the return value of the two numbers (int AddFunc (int a, int B ))
Copy the DLL to the folder to be generated by the exe.
2: Remember to add using System in C sharp code. runtime. interopServices (otherwise, use the [DllImport ("Test. dll ")], The following error message is displayed: The type oro namespace name 'dllimpt' could not be found.
3: The Wpf Test code is as follows. Click the Test button to go to The Button_Click_Test () function. One-Step debugging shows that TestValue is 8, indicating that the DLL call is successful.
[Csharp]
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading. Tasks;
Using System. Windows;
Using System. Windows. Controls;
Using System. Windows. Data;
Using System. Windows. Documents;
Using System. Windows. Input;
Using System. Windows. Media;
Using System. Windows. Media. Imaging;
Using System. Windows. Navigation;
Using System. Windows. Shapes;
Using System. Runtime. InteropServices; // Add
Namespace WpfApplication
{
/// <Summary>
/// Interaction logic for MainWindow. xaml
/// </Summary>
Public partial class MainWindow: Window
{
Public MainWindow ()
{
InitializeComponent ();
}
[DllImport ("Test. dll")] // load Test. dll
Public static extern AddFunc (int a, int B); // you can directly call the interface function provided by the DLL.
Private void Button_Click_Test (object sender, RoutedEventArgs e)
{
Int TestValue = 0;
TestValue = AddFunc (3, 5 );
Return;
}
}
}
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading. Tasks;
Using System. Windows;
Using System. Windows. Controls;
Using System. Windows. Data;
Using System. Windows. Documents;
Using System. Windows. Input;
Using System. Windows. Media;
Using System. Windows. Media. Imaging;
Using System. Windows. Navigation;
Using System. Windows. Shapes;
Using System. Runtime. InteropServices; // Add
Namespace WpfApplication
{
/// <Summary>
/// Interaction logic for MainWindow. xaml
/// </Summary>
Public partial class MainWindow: Window
{
Public MainWindow ()
{
InitializeComponent ();
}
[DllImport ("Test. dll")] // load Test. dll
Public static extern AddFunc (int a, int B); // you can directly call the interface function provided by the DLL.
Private void Button_Click_Test (object sender, RoutedEventArgs e)
{
Int TestValue = 0;
TestValue = AddFunc (3, 5 );
Return;
}
}
}