How to use the extern keyword in C#?
In C#, the “extern” keyword is used to declare an external method, which is a function or method written in another language. External methods can be referenced from an external library using the DllImport attribute. Here is an example of how the “extern” keyword is used:
using System;
using System.Runtime.InteropServices;
class Program
{
// 声明外部方法
[DllImport("user32.dll", SetLastError = true)]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
static void Main()
{
// 调用外部方法
MessageBox(IntPtr.Zero, "Hello World!", "Message Box", 0);
}
}
In the example above, an external method MessageBox is declared using the extern keyword, and the MessageBox function in the user32.dll library is referenced using the DllImport attribute. The MessageBox method is then called in the Main method to display a message box.