vc++中编写Dll,在C#(WPF)中引用

来源:互联网 发布:知乎的应用场景 编辑:程序博客网 时间:2024/06/11 22:39

在VC++中写Dll,然后在C#(WPF)中引用. 我这样做的初衷是因为用WPF设计软件的界面比较好看,也方便.

用VC++写的程序效率较高,移植性好,关键是其他几个同事擅长的是Vc++.合作开发的一个不错的选择就是用dll把各种功能模块汇聚到WPF的界面下.

1 首先,打开VS2010,新建一个VC++的类库工程.

1

2 新建完成之后打开MyVCLibrary.h,添加示例类的声明.

复制代码
// MyVCLibrary.h#pragma onceusing namespace System;namespace MyVCLibrary {    public ref class MathFuc    {        // TODO: 在此处添加此类的方法。        public:        // Returns a + b           double Add(double a, double b);        // Returns a - b           double Subtract(double a, double b);        // Returns a * b         double Multiply(double a, double b);        // Returns a / b        // Throws DivideByZeroException if b is 0          double Divide(double a, double b);    };}
复制代码

打开MyVCLibrary.cpp 加入类方法的具体实现:

复制代码
// 这是主 DLL 文件。#include "stdafx.h"#include "MyVCLibrary.h"#include <stdexcept>using namespace std;namespace MyVCLibrary{     double MathFuc::Add(double a, double b)    {        return a + b;    }    double MathFuc::Subtract(double a, double b)    {        return a - b;    }    double MathFuc::Multiply(double a, double b)    {        return a * b;    }    double MathFuc::Divide(double a, double b)    {        if (b == 0)        {            throw new invalid_argument("b cannot be zero!");        }        return a / b;    }}
复制代码

编译,在工程的debug目录下就会输出一个MyVCLibrary.dll文件.

3 接下来新建一个名为TestWindow的WPF工程对我们刚才生成的dll经行测试.

点击引用==>添加引用,将刚才vc类库的输出添加进来

在MainWindow.xaml加入一个RichTextbox由于显示测试结果

复制代码
<Window x:Class="TestWindow.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"        Loaded="Window_Loaded">    <Grid>        <RichTextBox Name="message" Margin="0"/>            </Grid></Window>
复制代码

测试代码如下:

复制代码
using System.Runtime.InteropServices;using System.Windows;namespace TestWindow{    /// <summary>    /// MainWindow.xaml 的交互逻辑    /// </summary>    public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();        }        //引入VC6.0 创建的dll文件中的函数        [DllImport("MyLibrary.dll", CallingConvention = CallingConvention.Cdecl)]        public static extern int Sum(int a,int b);        private void Window_Loaded(object sender, RoutedEventArgs e)        {            MyVCLibrary.MathFuc mathFuc = new MyVCLibrary.MathFuc();            message.AppendText("1+2="+mathFuc.Add(1,2)+"\r\n");            message.AppendText("5-4=" + mathFuc.Subtract(5,4) + "\r\n");            message.AppendText("2*42=" + mathFuc.Multiply(2,4) + "\r\n");            message.AppendText("10/3=" + mathFuc.Divide(10,3) + "\r\n");            message.AppendText("VC6.0 编写的库文件 sum(3,4)=" + Sum(3, 4) + "\r\n");        }    }}
复制代码

结果如下

实验成功.

工程附上.里面还以一个用vc6.0编写dll然后在WPF里面调用的例子,希望对大家有用.

文件名:vc6.0动态链接库编程示例及说明.rar, 访问地址:http://www.kuaipan.cn/file/id_25704335589509048.htm

原创粉丝点击