1 extern modifier is with the DllImport attribute when you are using Interop services to call into unmanaged code." data-guid="3ddb5debcf20ef3f259dbbcf5aaa2677">extern 修饰符的常见用法是在使用 Interop 服务调入非托管代码时与 DllImport 特性一起使用。 static, as shown in the following example:" data-guid="af016709ca53e6ded20f16c284c43bcd">在这种情况下,还必须将方法声明为 static,如下示例所示:
[DllImport("avifil32.dll")] private static extern void AVIFileInit();
注释:[DllImport("avifil32.dll")],这个特性用于指定相关方法的dll,一般情况下这个.dll是c语言写的(如果是c++,.dll中的方法名称
可能会由于类型修饰符的添加而发生改变)
例子:
(DllImport的命名空间)//using System.Runtime.InteropServices; class ExternTest { [DllImport("User32.dll", CharSet=CharSet.Unicode)] public static extern int MessageBox(IntPtr h, string m, string c, int type); static int Main() { string myString; Console.Write("Enter your message: "); myString = Console.ReadLine(); return MessageBox((IntPtr)0, myString, "My Message Box", 0); } }此示例使用 C 程序创建一个 DLL,在下一示例中将从 C# 程序调用该 DLL。
// cmdll.c // Compile with: /LD int __declspec(dllexport) SampleMethod(int i) { return i*10; }CM.cs and Cmdll.c, to demonstrate extern." data-guid="60bf736d478a751e3e86d5cd037dd70c">该示例使用两个文件 CM.cs 和 Cmdll.c 来说明 extern。 C 文件是示例 2 中创建的外部 DLL,它从 C# 程序内调用。CM.cs and Cmdll.c, to demonstrate extern." data-guid="60bf736d478a751e3e86d5cd037dd70c"><//www.w3.org/1999/xhtml:sentencetext xmlns="http://www.w3.org/1999/xhtml">// cm.cs using System; using System.Runtime.InteropServices; public class MainClass { [DllImport("Cmdll.dll")] public static extern int SampleMethod(int x); static void Main() { Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5)); } }2 extern 关键字还可以定义外部程序集别名可能必须引用两个具有相同完全限定类型名的程序集版本。 例如,可能必须在同一应用程序中使用程序集的两个或多个版本。
通过使用外部程序集别名,可以将来自每个程序集的命名空间包装在由别名命名的根级别命名空间中,
<//www.w3.org/1999/xhtml:sentencetext xmlns="http://www.w3.org/1999/xhtml">从而使这些命名空间可以在同一文件中使用。
完全限定类型名:要为各种反射操作提供有效的输入,必须指定类型名称。完全限定的类型名称包含程序集名称说明、命名空间说明和类型名称。/r:GridV1=grid.dll
/r:GridV2=grid20.dll
extern alias GridV1;
extern alias GridV2;
GridV1::Grid 是来自 grid.dll 的网格控件,而 GridV2::Grid 是来自 grid20.dll 的网格控件。
extern modifier is with the DllImport attribute when you are using Interop services to call into unmanaged code." data-guid="3ddb5debcf20ef3f259dbbcf5aaa2677">static, as shown in the following example:" data-guid="af016709ca53e6ded20f16c284c43bcd"><//www.w3.org/1999/xhtml:sentencetext xmlns="http://www.w3.org/1999/xhtml">