BlockLiteral Struct

Definition

Wraps an ECMA CLI delegate (C# lambdas, anonymous methods, or delegates) as an Objective-C block.

public struct BlockLiteral : IDisposable
type BlockLiteral = struct
    interface IDisposable
Inheritance
BlockLiteral
Implements

Remarks

This is a low-level class that is automatically used when using Objective-C block APIs.

In the C#/ECMA CLI world, delegates are automatically turned into blocks that can be consumed by Objective-C block-aware APIs.

If you need to P/Invoke a native C method that takes a block parameter, you would need to manually setup the BlockLiteral object and declare a proxy method that is invoked by the block handler and will invoke your managed code.

// Imagine that you want to invoke the following method:
// void SetupHandler (void (^block)(double offset, int count));

// Declare a trampoline method, which is the method that will be called when
// the block is invoked. The trampoline method must have an [UnmanagedCallersOnly]
// attribute, so that it can be called directly from native code.
[UnmanagedCallersOnly]
static void TrampolineHandler (IntPtr block, double offset, int count)
{
    // Find the delegate for the block and call it
    var callback = BlockLiteral.GetTarget<SetupHandlerCallback> (block);
    if (callback is not null)
        callback (offset, count);
}

[DllImport ("YourLibrary")]
unsafe static extern void SetupHandler (BlockLiteral* block);

public void SetupHandler (SetupHandlerCallback callback)
{
    if (callback is null)
        throw new ArgumentNullException (nameof (callback));
    delegate* unmanaged<IntPtr, double, int, void> trampoline = &TrampolineHandler;
    using var block = new BlockLiteral (trampoline, callback, GetType (), nameof (TrampolineHandler));
    SetupHandler (&block);
}

Constructors

Name Description
BlockLiteral(Void*, Object, MethodInfo)

Creates a block literal.

BlockLiteral(Void*, Object, String)

Creates a block literal.

BlockLiteral(Void*, Object, Type, String)

Creates a block literal.

Properties

Name Description
Context

Gets the context value that was specified when creating the BlockLiteral.

Target

Gets the target object for the block.

Methods

Name Description
CleanupBlock()

Releases the resources associated with this block.

Dispose()

Releases the resources associated with this block.

GetDelegateForBlock<T>()

Returns a managed delegate of type T that can invoke the native block.

GetTarget<T>(IntPtr)

Returns the managed delegate represented by the specified block.

IsManagedBlock(IntPtr)

Determines whether the specified block wraps a managed delegate.

SetupBlock(Delegate, Delegate)

Sets up a block using a trampoline and a user delegate.

SetupBlockUnsafe(Delegate, Delegate)

Sets up a block using a trampoline and a user delegate.

Applies to