The platform invoke (often abbreviated as PInvoke) feature of .NET enables .NET code to call functions from unmanaged libraries such as the Win32 API. The following example lets you see this in detail:
Note the use of the CharSet.Auto parameter in the DllImport attribute of the GetComputerName() method declaration. You might know that many Windows API calls come in two versions, depending on the character set you're using. For example, GetComputerName really exists as GetComputerNameA (for ANSI characters ) and GetComputerNameW (for Unicode characters). The Auto modifier instructs the .NET Framework to use the appropriate version of the API call for the platform on which the code is running.
PInvoke can also handle API calls that require structures as parameters. For example, many API calls require a Rect structure, which consists of four members filled in with the coordinates of a rectangle. In Visual C# .NET, you can declare a structure with explicit byte offsets for each member, which lets you define any structure the Windows API requires, like so: [StructLayout(LayoutKind.Explicit)] public struct Rect { [FieldOffset(0)] public Int32 left; [FieldOffset(4)] public Int32 top; [FieldOffset(8)] public Int32 right; [FieldOffset(12)] public Int32 bottom; } The StructLayout attribute tells the Visual C# .NET compiler that you'll explicitly specify the location of the individual fields in the structure. The FieldOffset attribute specifies the starting byte of each field in the structure. By using these attributes, you can ensure that the .NET Framework constructs the same structure the API function is expecting to receive. |