C# Programming/Keywords/extern
The keyword extern
indicates that the method being called exists in a DLL.
A tool called tlbimp.exe
can create a wrapper assembly that allows C# to interact with the DLL like it was a .NET assembly i.e. use constructors to instantiate it, call its methods.
Older DLLs will not work with this method. Instead, you have to explicitally tell the compiler what DLL to call, what method to call and what parameters to pass. Since parameter type is very important, you can also explicitly define what type the parameter should be passed to the method as.
Here is an example:
using System;
using System.Runtime.InteropServices;
namespace ExternKeyword
{
public class Program
{
static void Main()
{
NativeMethods.MessageBoxEx(IntPtr.Zero, "Hello there", "Caption here", 0, 0);
}
}
public class NativeMethods
{
[DllImport("user32.dll")]
public static extern MessageBoxEx(IntPtr hWnd, string lpText, string lpCaption, uint uType, short wLanguageId);
}
}
The [DllImport("user32.dll")]
tells the compiler which DLL to reference. Windows searches for files as defined by the PATH environment variable, and therefore will search those paths before failing.
The method is also static because the DLL may not understand how to be "created", as DLLs can be created in different languages. This allows the method to be called directly, instead of being instantiated and then used.
C# Keywords | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Special C# Identifiers (Contextual Keywords) | |||||||||||||||
| |||||||||||||||
Contextual Keywords (Used in Queries) | |||||||||||||||
|