Skip to content

Can I convert a delegate to a C# function pointer? (eg. delegate* managed<void>) #84026

Answered by DaZombieKiller
cyraid asked this question in Q&A
Discussion options

You must be logged in to vote

You can currently only do this if the delegate has no target, is not a DynamicMethod and is static (as far as I know):

static bool TryGetFunctionPointer(Delegate d, out void* pointer)
{
    ArgumentNullException.ThrowIfNull(d);
    var method = d.Method;

    if (d.Target is {} || !method.IsStatic || method is DynamicMethod)
    {
        pointer = null;
        return false;
    }

    pointer = (void*)method.MethodHandle.GetFunctionPointer();
    return true;
}

SharpLab Sample

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@cyraid
Comment options

Answer selected by cyraid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants