Show toolbar

2012年11月5日 星期一

C# WPF Call VC++ DLL

標題:C# WPF呼叫C++ DLL動態函式庫
C++ (CppDLL.h):
1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma once
using namespace System;
namespace CppDLL {
public ref class MyClass
{
public:
int Multiply(int x, int y)
{
return x * y;
}
};
}

WPF (MainWindow.xaml):
1
2
3
4
5
6
7
8
9
<Window x:Class="CSharpCaller.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Click Me" Height="30" HorizontalAlignment="Left" Margin="20,20,0,0" Name="btn" VerticalAlignment="Top" Width="100" Click="btn_Click" />
<TextBlock Height="30" HorizontalAlignment="Left" Margin="20,70,0,0" Name="tbk" Text="Show up here" VerticalAlignment="Top" Width="100" />
</Grid>
</Window>

C# (MainWindow.xaml.cs):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
namespace CSharpCaller
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btn_Click(object sender, RoutedEventArgs e)
{
CppDLL.MyClass test = new CppDLL.MyClass();
tbk.Text = test.Multiply(2, 4).ToString();
}
}
}

結果:

說明:
使用C# WPF呼叫C++函式庫進行乘法運算的簡單範例,
建立Visual C++ CLR Class Library專案,編譯DLL函式庫,
建立Visual C# WPF Application專案,加入References的DLL檔案,
編譯後即可執行。