17.5 Callbacks from Unmanaged Code
The P/Invoke layer does its best to present a natural
programming model on both sides of the boundary, mapping between the
relevant constructs where possible. Since C# not only can call out to
C functions but can also be called back from the C functions (via
function pointers), the P/Invoke layer needs to map unmanaged
function pointers onto something natural for the managed world. The
managed equivalent of a function pointer is a delegate, so the
P/Invoke layer automatically maps between delegates (in C#) and
function pointers (in C). To call a function in a DLL that takes a
callback function pointer as a parameter, declare a delegate with the
correct signature for the callback function and pass an instance of
the delegate when calling the function that performs the callback, as
follows:
using System;
using System.Runtime.InteropServices;
class CallbackFun {
delegate bool CallBack(int hWnd, int lParam);
[DllImport("user32.dll")]
static extern int EnumWindows(CallBack hWnd, int lParam);
static bool PrintWindow(int hWnd, int lParam) {
Console.WriteLine(hWnd);
return true;
}
static void Main( ) {
CallBack e = new CallBack(PrintWindow);
EnumWindows(e, 0);
}
}
|