基于C#的接口基础教程之六(5)
点击次数:26 次 发布日期:2008-11-27 00:02:05 作者:源代码网
|
源代码网推荐 源代码网推荐 .NET 框架程序可以通过静态 DLL 入口点的方式来访问本机代码库。DllImport 属性用于指定包含外部方法的实现的dll 位置。 源代码网推荐 源代码网推荐 DllImport 属性定义如下: 源代码网推荐 源代码网推荐 namespace System.Runtime.InteropServices 源代码网推荐 { 源代码网推荐 [AttributeUsage(AttributeTargets.Method)] 源代码网推荐 public class DllImportAttribute: System.Attribute 源代码网推荐 { 源代码网推荐 public DllImportAttribute(string dllName) {...} 源代码网推荐 public CallingConvention CallingConvention; 源代码网推荐 public CharSet CharSet; 源代码网推荐 public string EntryPoint; 源代码网推荐 public bool ExactSpelling; 源代码网推荐 public bool PreserveSig; 源代码网推荐 public bool SetLastError; 源代码网推荐 public string Value { get {...} } 源代码网推荐 } 源代码网推荐 } 源代码网推荐 源代码网推荐 说明: 源代码网推荐 源代码网推荐 1、DllImport只能放置在方法声明上。 源代码网推荐 源代码网推荐 2、DllImport具有单个定位参数:指定包含被导入方法的 dll 名称的 dllName 参数。 源代码网推荐 源代码网推荐 3、DllImport具有五个命名参数: 源代码网推荐 源代码网推荐 a、CallingConvention 参数指示入口点的调用约定。如果未指定 CallingConvention,则使用默认值 CallingConvention.Winapi。 源代码网推荐 源代码网推荐 b、CharSet 参数指示用在入口点中的字符集。如果未指定 CharSet,则使用默认值 CharSet.Auto。 源代码网推荐 源代码网推荐 c、EntryPoint 参数给出 dll 中入口点的名称。如果未指定 EntryPoint,则使用方法本身的名称。 源代码网推荐 源代码网推荐 d、ExactSpelling 参数指示 EntryPoint 是否必须与指示的入口点的拼写完全匹配。如果未指定 ExactSpelling,则使用默认值 false。 源代码网推荐 源代码网推荐 e、PreserveSig 参数指示方法的签名应当被保留还是被转换。当签名被转换时,它被转换为一个具有 HRESULT 返回值和该返回值的一个名为 retval 的附加输出参数的签名。如果未指定 PreserveSig,则使用默认值 true。 源代码网推荐 源代码网推荐 f、SetLastError 参数指示方法是否保留 Win32"上一错误"。如果未指定 SetLastError,则使用默认值 false。 源代码网推荐 源代码网推荐 4、它是一次性属性类。 源代码网推荐 源代码网推荐 5、此外,用 DllImport 属性修饰的方法必须具有 extern 修饰符。 源代码网推荐 源代码网推荐 下面是 C# 调用 Win32 MessageBox 函数的示例: 源代码网推荐 源代码网推荐 using System; 源代码网推荐 using System.Runtime.InteropServices; 源代码网推荐 class MainApp 源代码网推荐 { //通过DllImport引用user32.dll类。MessageBox来自于user32.dll类 源代码网推荐 [DllImport("user32.dll", EntryPoint="MessageBox")] 源代码网推荐 public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType); 源代码网推荐 public static void Main() 源代码网推荐 { 源代码网推荐 MessageBox( 0, "您好,这是 PInvoke!", ".NET", 0 ); 源代码网推荐 } 源代码网推荐 } 源代码网推荐 源代码网推荐 面向对象的编程语言几乎都用到了抽象类这一概念,抽象类为实现抽象事物提供了更大的灵活性。C#也不例外, C#通过覆盖虚接口的技术深化了抽象类的应用。欲了解这方面的知识,请看下一节-覆盖虚接口 源代码网推荐 源代码网供稿. |
