Description
Background and motivation
IL has always exposed ldtoken
instruction, but C# only exposed the type variant of it, making the method and field variants inaccessible. Requests for exposing those have been denied for either unclear semantics or the language team disliking the fact it'd promote reflection.
With the handles being useful for some low level code and exposing things like function pointers, I'd say there's still value in adding a way for cheaply obtaining them with trimming and AOT friendly, fast and visiblity-ignoring way. UnsafeAccessor
s from #81741 meets all 3 criteria (unlike reflection or IL weaving without IgnoreAccessChecksTo).
One question would be whether those should return RuntimeXHandle
s or XInfo
s, since the API is low level and there are existing APIs to get XInfo
s from handles, I'd suggest it to be the former.
Since IL exposes return type overloading on methods and fields (the latter is non CLS compliant though), the signature would need to indicate the type of those, for example with a dummy parameter at the end. The issue with this would be methods returning void.
If field Offset
would be exposed on RuntimeFieldInfo
in #94976, this could supersede #93946.
API Proposal
namespace System.Runtime.CompilerServices;
public enum UnsafeAccessorKind
{
StaticFieldHandle, // handle to static field on the type (`ldtoken` in IL)
FieldHandle, // handle to instance field on the type (`ldtoken` in IL)
StaticMethodHandle, // handle to static method on the type (`ldtoken` in IL)
MethodHandle, // handle to instance method on the type (`ldtoken` in IL)
VirtualMethodHandle // same as InstanceMethodHandle but with virtual method resolving on the object instance, let's you emulate `ldvirtftn`
}
API Usage
public class C
{
private int i;
protected virtual string B() => "C";
}
public class D : C
{
protected override void B() => "D";
}
[UnsafeAccessor(UnsafeAccessorKind.InstanceFieldHandled, Name = "i")]
public static RuntimeFieldHandle GetI(C c = null, int i = 0);
[UnsafeAccessor(UnsafeAccessorKind.InstanceMethodHandled, Name = "B")]
public static RuntimeMethodHandle GetB(C c = null, string s = null);
[UnsafeAccessor(UnsafeAccessorKind.VirtualMethodHandled, Name = "B")]
public static RuntimeMethodHandle GetBVirtual(C c, string s = null);
Console.WriteLine(FieldInfo.GetFieldFromHandle(GetI()).Attributes);
Console.WriteLine(MethodBase.GetMethodFromHandle(GetB())); // prints C.B
Console.WriteLine(MethodBase.GetMethodFromHandle(GetBVirtual(new D()))); // prints D.B
Alternative Designs
Exposing infoof/methodof/fieldof
and IgnoreAccessChecksTo
would be a possible alternative but both have already been rejected.
Risks
Popularising reflection use.