Monday, October 26, 2009

Interoperating with Unmanaged Code Example-Using Delegate to Call Back Functions in Managed Code

We know that to call an unmanaged function in a COM object, We need to do:
1. Add DllImportAttribute
2. Create a prototype method for the COM function

like:
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern int MessageBox(int hWnd, String text,
String caption, uint type);


But when the unmanaged function has long pointer parameter?

Here is an example easy to be found in msdn:

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);
return true;
}
}


The COM Fuction BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam), notice that if the argument is begin with lp-(long pointer)prefix, this is a function require a call back in COM.

To call a function that requires a callback, follow these steps:
1. Create a method to handle the callback.
2. Create a delegate for the method.
3. Create a prototype for the function, specifying the delegate for the callback
argument.
4. Call the function.

See the references:
http://msdn.microsoft.com/en-us/library/d186xcf0(VS.71).aspx
http://www.pinvoke.net/default.aspx/user32.EnumWindows

No comments: