System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer Method

Converts an unmanaged function pointer to a delegate.

Syntax

public static Delegate GetDelegateForFunctionPointer (IntPtr ptr, Type t)

Parameters

ptr
The unmanaged function pointer to be converted.
t
The type of the delegate to be returned.

Returns

A delegate instance that can be cast to the appropriate delegate type.

Remarks

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 Marshal.GetDelegateForFunctionPointer(IntPtr, Type) and Marshal.GetFunctionPointerForDelegate(Delegate) methods to marshal delegates in both directions. With Marshal.GetDelegateForFunctionPointer(IntPtr, Type), ptr is imported as a IntPtr. A IntPtr can be obtained for a managed delegate by calling Marshal.GetFunctionPointerForDelegate(Delegate) and passed as a parameter; it can then 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 Marshal.GetDelegateForFunctionPointer(IntPtr, Type) 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 RuntimeMethodHandle.GetFunctionPointer method.

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

Requirements

Namespace: System.Runtime.InteropServices
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 2.0.0.0, 4.0.0.0
Since: .NET 2.0