ExternModifier is used to declare methods for external implementation.ExternThe common usage of modifiers isDllimportIn this case, the method must also be declaredStatic, As shown in the following example:
[Dllimport ("avifil32.dll")]
Private Static extern void avifileinit ();
ExternYou can also define the alias of an external Assembly so that different versions of the same component can be referenced from a single assembly. For more information, see external alias (C # reference ).
Abstract (C # reference) andExternIt is wrong to use modifiers together to modify the same member. UseExternModifier means that the method is implemented outside the C # code, andAbstractModifier means that method implementation is not provided in the class.
ExternKeyword usage has more restrictions than C ++. To compare with the c ++ keyword, see using extern to specify linkage in C ++ language reference.
Example:
In this example, the program receives a string from the user and displays the string in the message box. Program usageUser32.dllLibrary importedMessageBoxMethod.
Copy
using System;using System.Runtime.InteropServices;class MainClass { [DllImport("User32.dll")] public static extern int MessageBox(int h, string m, string c, int type); static int Main() { string myString; Console.Write("Enter your message: "); myString = Console.ReadLine(); return MessageBox(0, myString, "My Message Box", 0); }}
This example uses the C program to create a DLL. In the next example, the DLL will be called from the C # program.
Copy
// cmdll.c// compile with: /LDint __declspec(dllexport) SampleMethod(int i){ return i*10;}
This example uses two filesCm. CSAndCmdll. cTo describeExtern. The C file is the external DLL created in example 2, which is called from the C # program.
Copy
// cm.csusing 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)); }}Output
SampleMethod() returns 50.
Note:
Generate a project:
This will create an executable fileCm.exe. When running this program,SamplemethodPass the value 5 to the DLL file, which is multiplied by 10 to return the value.