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
{
///
/// 必需的设计器变量。
///
private System.ComponentModel.IContainer components = null;
///
/// 清理所有正在使用的资源。
///
/// 如果应释放托管资源,为 true;否则为 false。
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
///
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
///
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();