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()

        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;

One 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.


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s