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

來源:互聯網
上載者:User

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;        }    }}

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.