C sharp中如何調用C++編寫的DLL

WPF大行其道,開發用戶界面確實非常方便。有時候需要調用很多以前用C++編寫的DLL庫,這就涉及到C sharp 中如何調用C++編寫的DLL的問題。一番嘗試之後,發現調用其實比較簡單。步驟記錄如下:

1:本例中DLL名稱爲:Test.dll,提供的接口函數也很簡單:兩數相加 返回和值(int AddFunc(int a, int b))

      將DLL拷貝到exe將要生成的文件夾下。

2:C sharp 代碼中記得添加using System.Runtime.InteropServices(否則的話 ,使用後文中提到的[DllImport("Test.dll")]時將會提示:The type oro namespace name'DllImport' could not be found的錯誤信息

3:Wpf 測試代碼如下,點擊Test按鈕之後,進入Button_Click_Test()函數,單步調試發現TestValue 爲8,說明DLL調用成功了。

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;    //添加
 

namespace WpfApplication
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }


        [DllImport("Test.dll")]                       //載入Test.dll
        public static extern AddFunc(int a, int b);   //引出DLL提供的接口函數之後,就可以直接調用了。
        private void Button_Click_Test(object sender, RoutedEventArgs e)
        {
            int TestValue = 0;

            TestValue = AddFunc(3, 5);

            return;
        }
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章