Tuesday, December 30, 2008

Interoperating with COM - Using COM from the .NET Framework (5)

How to Implement Callback Functions

Sometimes, you need to implement a function inside a managed application for unmanaged function to call to complete the task. That is a "Callback" function.

Calls to a callback function pass indirectly from a managed application, through a DLL function, and back to the managed implementation. Basically, you create a callback function in your managed application, and then call the DLL function with passing a pointer to the callback function as an argument.


Callback functions are ideal for use in situations in which a task is performed repeatedly. For example, The EnumWindows function enumerates through all existing windows on your computer, calling the callback function to perform a task on each window:

//One clue that this function requires a callback is the presence of the lpEnumFunc argument. It is common to see the lp (long pointer) prefix combined with the Func suffix in the name of arguments that take a pointer to a callback function.
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam)

Simple steps:
  1. Create a function to handle callback task.
  2. Create a delegate for this function.
  3. Create a prototype for the COM unmanaged function, and specify the delegate as the callback function argument.
  4. Call the COM unmanaged function.
Example:
using System;
using System.Runtime.InteropServices;
//step 2
public delegate bool CallBack(int hwnd, int lParam);
public class EnumReportApp
{
//step 3
[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);
public static void Main()
{
//step 4
CallBack myCallBack = new CallBack(EnumReportApp.Report);
EnumWindows(myCallBack, 0);
}
//step 1
public static bool Report(int hwnd, int lParam)
{
Console.Write("Window handle is ");
Console.WriteLine(hwnd);
return true;
}
}
For more information, please refer to MSDN:
Callback Functions
How to: Implement Callback Functions

No comments:

Post a Comment