Search This Blog

Wednesday, July 3, 2013

Callback Functions

A callback function is code within a managed application that helps an unmanaged DLL function complete a task. Calls to a callback function pass indirectly from a managed application, through a DLL function, and back to the managed implementation. Some of the many DLL functions called with platform invoke require a callback function in managed code to run properly.
Generally speaking a callback is executable code that is passed as an argument to other code

See in the following function's signature:
              BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam)  
lp prefix comes from the long pointer term.Thus the lpEnumFunc is a pointer to a callback function.

The EnumWindows function enumerates through all existing windows on your computer, calling the callback function to perform a task on each window. Thiw function belongs to the Win32 API (user32.dll).
Also,in the following example:
EnumWindows  unmanaged DLL function. 
CallBack(int hwnd, int lparam) is the managed  callback function
hwnd:handle to the window
lparam:application defined parameter

using System;
using System.Runtime.InteropServices;

public delegate bool CallBack(int hwnd, int lParam);

public class EnumReportApp
{
    [DllImport("user32")]
    public static extern int EnumWindows(CallBack x, int y); 

    public static void Main() 
    {
        CallBack myCallBack = new CallBack(EnumReportApp.Report);
        EnumWindows(myCallBack, 0);
    }

    public static bool Report(int hwnd, int lParam)
    { 
        Console.Write("Window handle is ");
        Console.WriteLine(hwnd);
        //Callback functions generally return nonzero values to indicate success         //and zero to indicate failure. This example explicitly sets the return v        //alue to true to continue the enumeration.

        return true;
    }
}

Similar enumeration functions are: EnumFontFamilies, EnumPrinters

The usage of a callback is usually in asynchronous logic.


No comments:

Post a Comment

About Me

An seasoned developer, architect and with some Team Leading exposure, offering full project life cycle experiences within multi cultural, multi National environments and within differing business streams and all primarily on a .Net platform.