CSharp Interview Questions

Platform Invoke – C#

Platform Invoke – C#

A platform invoke call to an unmanaged DLL function

When platform invoke calls an unmanaged function, it performs the following sequence of actions:

  1. Locates the DLL containing the function.
  2. Loads the DLL into memory.
  3. Locates the address of the function in memory and pushes its arguments onto the stack, marshaling data as required.

    Note   Locating and loading the DLL, and locating the address of the function in memory occur only on the first call to the function.

  4. Transfers control to the unmanaged function.

Platform Invoke example below :

using System.Runtime.InteropServices;

public class Win32 {
     [DllImport(“user32.dll”, CharSet=CharSet.Auto)]
     public static extern int MessageBox(int hWnd, String text,
                     String caption, uint type);
}

public class HelloWorld {
    public static void Main() {
       Win32.MessageBox(0, “Hello World”, “Platform Invoke Sample”, 0);
    }
}     

Leave a Reply