Welcome to Bangladesh Microsoft Technology Community Sign in | Join | Help

Design Pattern for P/Invoke Dll from c#

http://www.pinvoke.net comes with handy C# /VB.Net signatures for invoking with core Win32 API.

for example if we search for MessageBox in http://www.pinvoke.net we get the following result:

C# Signature (Original):

[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern uint MessageBox(IntPtr hWnd, String text, String caption, uint type);

This is the bare minimum and we can use this straight way in our application but I always prefer to write a Wrapper around it. Which turns into something like this:

sealed class MessageBoxWrapper
{
  private MessageBoxWrapper(){}

  public static void MessageBox(int h, string message, string errorMessage, MessageBoxStyles style)
  {
    if (MessageBox(new IntPtr(h), message, errorMessage, (uint)style) < 1)
    {
      Int32 err = Marshal.GetLastWin32Error();
      throw new Win32Exception(err);
    }
  }
  [DllImport("user32.dll",CharSet=CharSet.Auto)]
  public static extern int MessageBox(IntPtr hWnd,String text,String caption, uint style);
}
enum MessageBoxStyles : uint
{
  MB_OK = 0x00000000,
  MB_OKCANCEL = 0x00000001,
  MB_YESNO = 0x00000004
}


Now you might be asking why a wrapper? There are couple of good reasons:
1. This avoids application logic to call externs directly.
2. The wrapper is also Sealed and has a private constructor so it prevents creation of instance of the wrapper by mistake.
3. Resusability of the Wrapper accross the application.
4. The hardcore api calls reside all inside the wrapper and developers using the wrapper do not need to know the nity gritty of the internals and can do .Net Style coding.
5. Use of enumerators and all magic numbers reside at a central location.
6. Opportunity to do Error Handling and also return Meaningful Errors.


And the following code show how to call the method:

static void Main(string[] args)
{
  MessageBoxWrapper.MessageBox(0,"Test","Error",MessageBoxStyles.MB_YESNO); 
}


I believe, its a very good practice/pattern to throw a wrapper around any extern methods.

Win 32 Api Reference

Published Monday, February 05, 2007 7:37 PM by Shahed

Comments

No Comments

Anonymous comments are disabled