17.1 Calling Into DLLs

PInvoke, short for Platform Invocation Services, lets C# access functions, structs, and callbacks in unmanaged DLLs. For example, perhaps you wish to call the MessageBox function in the Windows DLL user32.dll:

int MessageBox(HWND hWnd, LPCTSTR lpText, 
               LPCTSTR lpCation, UINT uType);

To call this function, you can write a static extern method decorated with the DllImport attribute:

using System.Runtime.InteropServices;
class MsgBoxTest {
  static extern int MessageBox(int hWnd, string text,
                               string caption, int type);
  public static void Main( ) {
    MessageBox(0, "Please do not press this button again.",
               "Attention", 0);

PInvoke then finds and loads the required Win32 DLLs and resolves the entry point of the requested function. The CLR includes a marshaler that knows how to convert parameters and return values between .NET types and unmanaged types. In this example the int parameters translate directly to four-byte integers that the function expects, and the string parameters are converted into null-terminated arrays of characters using one-byte ANSI characters under Win9x, or into two-byte Unicode characters under WinNT/Win2K.

    Part II: Programming with the .NET Framework
    Part IV: API Quick Reference