-
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)]
publicstaticexternboolMoveFile(Stringsrc,Stringdst);
KERNEL32.DLL其中为DLL文件,extern 修饰符用于声明在外部实现的方法(本示例为MoveFileW方法)。在以上代码中,涉及到参数说明如下表所示。
表 DllImport属性参数说明
名称
|
说明
|
CallingConvention
|
指示入口点的调用约定
|
CharSet
|
指示如何向方法封送字符串参数,并控制名称重整
|
EntryPoint
|
指示要调用的DLL入口点的名称或序号
|
PreserveSig
|
指示签名是否为非托管入口点的直接转换
|
SetLastError
|
指示被调用方在从属性化方法返回之前是否调用 SetLastError Win32 API 函数
|
本示例调用非托管的projectdll.dll文件,并使用Sum方法实现加法运算。
程序代码如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Runtime.InteropServices;
namespace_4_03
{
publicpartialclassForm1:Form
{
publicclasscCdll
{
[DllImport("projectdll.dll",EntryPoint="Sum",SetLastError=true,CharSet=CharSet.Unicode,ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]
publicstaticexterndoubleSum(doublex,doubley);
}
publicForm1()
{
InitializeComponent();
}
privatevoidbutton1_Click(objectsender,EventArgse)
{
textBox3.Text=cCdll.Sum(Convert.ToDouble(textBox1.Text),Convert.ToDouble(textBox2.Text)).ToString();
}
}
}