Passing managed delegates to native functions as callbacks

In one of the hands-on labs here at MEDC a developer asked how to pass a managed funtion to a native DLL as a callback function.  I promised him a sample, so here’s a simple one that shows how to call EnumWindows:

public delegate int EnumWindowsProc(IntPtr hwnd, IntPtr lParam);

public partial class Form1 : Form
{
    EnumWindowsProc callbackDelegate;
    IntPtr callbackDelegatePointer;

    [DllImport("coredll.dll", SetLastError = true)]
    public static extern bool EnumWindows(IntPtr lpEnumFunc, uint lParam);

    public Form1()
    {
        InitializeComponent();

        callbackDelegate = new EnumWindowsProc(EnumWindowsCallbackProc);
        callbackDelegatePointer = Marshal.GetFunctionPointerForDelegate(callbackDelegate);

        EnumWindows(callbackDelegatePointer, 0);
    }

    public int EnumWindowsCallbackProc(IntPtr hwnd, IntPtr lParam)
    {
        System.Diagnostics.Debug.WriteLine(“Window: “ + hwnd.ToString());

        return 1;
    }
}

1 thought on “Passing managed delegates to native functions as callbacks”

  1. Thanks for the example. I am running into a little problem. I can’t find the call GetFunctionPointerForDelegate() in my version of c# for Marshal. What do I need? I am using the Compact Framework.

    Thanks in advance.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s