Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
All articles(文章集合)All Picture(图片集合)All Video(视频集合)
The author:(作者)qqpublished in(发表于) 2014/7/11 9:21:57 C#教程:C#调用其他编程语言编写的DLL
C#教程:C#调用其他编程语言编写的DLL
C#调用其他编程语言编写的DLL在程序开发过程,有时会使用C#调用其他编程语言开发的DLL或调用Windows系统API函数,由于这些DLL都属于非托管动态链接库(DLL),要调用非托管动态链接库(DLL)则需要使用DllImport属性。DllImport属性指示该属性化方法由非托管动态链接库(DLL)作为静态入口点公开,并提供对从非托管DLL导出的函数进行调用所必需的信息。作为最低要求,必须提供包含入口点的DLL的名称。在使用DllImport属性前,须引用命名空间System.Runtime.InteropServices。下面的示例说明如何使用DllImport属性调用非托管的DLL。代码如下:[DllImport("KERNEL32.DLL", EntryPoint="MoveFileW", SetLastError=True,CharSet=CharSet.Unicode, ExactSpelling=True,CallingConvention=CallingConvention.StdCall)]public static extern bool MoveFile(String src, String dst);其中KERNEL32.DLL为DLL文件,extern 修饰符用于声明在外部实现的方法(本示例为MoveFileW方法)。在以上代码中,涉及的参数及说明如表1所示。表1 DllImport属性参数及说明示例C#调用Delphi语言编写的DLL本示例调用非托管的projectdll.dll文件,并使用Sum方法实现加法运算,如图.1所示。图1 C#调用Delphi语言编写的DLL实现加法运算程序代码如下:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace _4_03{public partial class Form1 : Form{public class cCdll{[DllImport("projectdll.dll", EntryPoint = "Sum", SetLastError = True, CharSet = CharSet.Unicode, ExactSpelling = True, CallingConvention = CallingConvention.StdCall)]public static extern double Sum(double x, double y);}public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){textBox3.Text = cCdll.Sum(Convert.ToDouble(textBox1.Text), Convert.ToDouble (textBox2.Text)). ToString();}}}完整程序代码如下:★ ★★★★Form1.cs窗体代码文件完整程序代码★★★★★using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;namespace _4_03{public partial class Form1 : Form{public class cCdll{[DllImport("projectdll.dll", EntryPoint = "Sum", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]public static extern double Sum(double x, double y);}public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){textBox3.Text = cCdll.Sum(Convert.ToDouble(textBox1.Text), Convert.ToDouble(textBox2.Text)).ToString();}}}★ ★★★★Form1.designer.cs窗体设计文件完整程序代码★★★★★namespace _4_03{partial class Form1{///