当前位置:编程学习 > C#/ASP.NET >>

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调用成功了。

 


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

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

 

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,