Posts Tagged: PInvoke


15
Oct 08

Learning PInvoke in c#

PInvoke is a mechanism used to invoke unmanaged code functions from managed code. It was primarily provided by Microsoft for porting functionality from COM to .net in cases where no equivalent methods for the same functionality were available.
This becomes a vital part of migration projects where an equivalent function is unavailable in the managed code framework.
For e.g. there remains no mechanism in .net to read Compound files. Compound files are structure files consisting of Storage and Stream objects which resemble a file system. It is a key data structure provided by COM.

How it works?
The following sequence of steps is followed during a typical PInvoke.

  • The Dll containing the unmanaged function is located.
  • This Dll is loaded into memory.
  • The memory address of the unmanaged function to be invoked is found out and the parameters are passed after marshalling.
  • The flow control is transferred to the unmanaged function and execution takes place.

However, the exceptions raised in the unmanaged functions are thrown to the managed caller.

A sample application
In this example, we make a PInvoke call to the MessageBox() method available in user32.dll. Lets go through the code.
Remember, for PInvoke to work, you need to use the System.Runtime.InteropServices namespace.

Create a console application with the following code.

using System.Runtime.InteropServices;

class Program
{
  public class Win32
  {
    //--Giving the prototype of the method to be PInvoked, specifying the dll which contains it..
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern int MessageBox(int hWnd, String text, String caption, uint type);
  }

  public static void Main(string[] args)
  {
  //--PInvoking.
  Win32.MessageBox(0,"This window has been created using a PInvoke call.","PInvokeSample", 0);
  }
}

Good luck to all .net programmers who wish to make function calls to unmanaged code.

Happy PInvoking!!