Can I convert a delegate to a C# function pointer? (eg. delegate* managed<void>) #84026
-
As the title suggests, is there a way to convert a delegate into a managed function pointer? (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/function-pointers) .. I'm using them, and they work great, but I don't want to use "&func" in an unsafe context, I was hoping the underlying method call could access it, and I can just provide a delegate. |
Beta Was this translation helpful? Give feedback.
Answered by
DaZombieKiller
Mar 28, 2023
Replies: 1 comment 1 reply
-
You can currently only do this if the delegate has no target, is not a 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;
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
cyraid
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can currently only do this if the delegate has no target, is not a
DynamicMethod
and is static (as far as I know):SharpLab Sample