This documentation is archived and is not being maintained.

Marshal.GetDelegateForFunctionPointer Method

Converts an unmanaged function pointer to a delegate.

Namespace:  System.Runtime.InteropServices
Assembly:  mscorlib (in mscorlib.dll)

[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static Delegate GetDelegateForFunctionPointer(
	IntPtr ptr,
	Type t
)

Parameters

ptr
Type: System.IntPtr

An System.IntPtr type that is the unmanaged function pointer to be converted.

t
Type: System.Type

The type of the delegate to be returned.

Return Value

Type: System.Delegate
A delegate instance that can be cast to the appropriate delegate type.

ExceptionCondition
ArgumentException

The t parameter is not a delegate or is generic.

ArgumentNullException

The ptr parameter is null.

-or-

The t parameter is null.

In versions 1.0 and 1.1 of the .NET Framework, it was possible to pass a delegate representing a managed method to unmanaged code as a function pointer, allowing the unmanaged code to call the managed method through the function pointer. It was also possible for the unmanaged code to pass that function pointer back to the managed code, and the pointer was resolved properly to the underlying managed method.

In the .NET Framework 2.0 and later versions, you can use the GetDelegateForFunctionPointer method, and the GetFunctionPointerForDelegate method to marshal delegates in both directions. With GetDelegateForFunctionPointer, ptr is imported as an IntPtr; an IntPtr can be obtained for a managed delegate by calling GetFunctionPointerForDelegate and passed as a parameter; then it can be called from inside the unmanaged method. Note that the parameter marshaler can also marshal function pointers to delegates in the .NET Framework 2.0 and later versions.

The GetDelegateForFunctionPointer method has the following restrictions:

  • Generics are not supported in interop scenarios.

  • You cannot pass an invalid function pointer to this method.

  • You can use this method only for pure unmanaged function pointers.

  • You cannot use this method with function pointers obtained through C++ or from the GetFunctionPointer method.

  • You cannot use this method to create a delegate from a function pointer to another managed delegate.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0
Show: