ILSpy icon indicating copy to clipboard operation
ILSpy copied to clipboard

Emit Unsafe.AsRef

Open wwh1004 opened this issue 5 years ago • 1 comments

Class3<T>.Method6

public unsafe static ref T Method6(ref T a)
{
	return ref *(T*)(long)(IntPtr)InterpreterStub.Dispatch(0, 100663305, new object[1]
	{
		(IntPtr)System.Runtime.CompilerServices.Unsafe.AsPointer(ref a)
	}, new Type[1]
	{
		typeof(T)
	}, null);
}

public static class InterpreterStub
{
	public static object Dispatch(int moduleId, int methodToken, object[] arguments, Type[] typeInstantiation, Type[] methodInstantiation)
	{
	}
}

how about emit Unsafe.AsRef instead of ref *(T*)(long)

stub.zip

wwh1004 avatar Sep 03 '20 12:09 wwh1004

Unsafe.AsRef expects a pointer type so we'd have to emit ref Unsafe.AsRef<T>((void*)(long)(IntPtr)InterpreterStub.Dispatch(...)). That doesn't make the code any more readable.

I guess using Unsafe.AsRef makes sense when converting to a reference to a managed type, where forming the pointer type T* isn't valid. But ILSpy currently doesn't have logic to detect whether a type would satisfy the T: unmanaged constraint.

dgrunwald avatar Sep 12 '20 15:09 dgrunwald