C sharp中如何调用C++编写的DLL

本文介绍如何在WPF应用程序中使用C++编写的DLL。通过具体实例演示了加载DLL、声明导出函数的过程,并给出完整的C#代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值