DllImport属性指示该属性化思路方法由非托管动态链接库(DLL)作为静态入口点公开并提供对从非托管DLL导出进行所必需信息作为最低要求必须提供包含入口点DLL名称在使用DllImport属性前须引用命名空间:.Runtime.InteropServices
下面举例介绍说明如何使用DllImport属性非托管DLL
[DllImport("KERNEL32.DLL",EntryPo="MoveFileW", SetLastError=true,
CharSet=CharSet.Unicode,ExactSpelling=true,
CallingConvention=CallingConvention.StdCall)]
publicexternboolMoveFile(Stringsrc,Stringdst);
KERNEL32.DLL其中为DLL文件extern 修饰符用于声明在外部实现思路方法(本举例为MoveFileW思路方法)在以上代码中涉及到参数介绍说明如下表所示
表 DllImport属性参数介绍说明
名称
介绍说明
CallingConvention
指示入口点约定
CharSet
指示如何向思路方法封送串参数并控制名称重整
EntryPo
指示要DLL入口点名称或序号
PreserveSig
指示签名是否为非托管入口点直接转换
SetLastError
指示被方在从属性化思路方法返回的前是否 SetLastError Win32 API
举例 C#Delphi语言编写DLL 本举例非托管projectdll.dll文件并使用Sum思路方法实现加法运算
代码如下:
using;
using.Collections.Generic;
using.ComponentModel;
using.Data;
using.Drawing;
using.Text;
using.Windows.Forms;
using.Runtime.InteropServices;
_4_03
{
publicpartialForm1:Form
{
publiccCdll
{
[DllImport("projectdll.dll",EntryPo="Sum",SetLastError=true,CharSet=CharSet.Unicode,ExactSpelling=true,CallingConvention=CallingConvention.StdCall)]
publicexterndoubleSum(doublex,doubley);
}
publicForm1
{
InitializeComponent;
}
privatevoidbutton1_Click(objectsender,EventArgse)
{
textBox3.Text=cCdll.Sum(Convert.ToDouble(textBox1.Text),Convert.ToDouble(textBox2.Text)).;
}
}
}
最新评论