Marshaling Delegates as Function Pointers

The following table shows examples of how a managed delegate can be marshaled to a function pointer in unmanaged code.

Managed delegate (C#)

Unmanaged function pointer (C+)

public delegate int EnumDelegate(
  IntPtr hwnd, int LParam);
[DllImport("coredll.dll")] 
static extern int EnumWindows(
  EnumDelegate d,
  Int lParm);
typedef BOOL (* WNDENUMPROC) 
  (HWND, LPARAM);
BOOL EnumWindows(
  WNDENUMPROC lpEnumFunc, 
  LPARAM lParam);
public delegate int EnumDelegate(
  IntPtr hwnd, int lParam);
[DllImport("coredll.dll")]
static extern int EnumWindows(
  [MarshalAs(UnmanagedType.FunctionPtr)]
  EnumDelegate d,
  Int lParam);
typedef BOOL (* WNDENUMPROC) 
  (HWND, LPARAM);
BOOL EnumWindows(
  WNDENUMPROC lpENumFunc,
  LPARAM lParam);

See Also

Other Resources

Marshaling Support in the .NET Compact Framework

Change History

Date

History

Reason

October 2008

Corrected typo in 2nd example.

Content bug fix.