-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnsafe.cs
More file actions
42 lines (31 loc) · 1.22 KB
/
Copy pathUnsafe.cs
File metadata and controls
42 lines (31 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace CsharpClassOnStack.Safe.Override;
internal static class Unsafe<T> where T : class
{
private delegate ref T UnsafeRefCastDelegate(ref Span<IntPtr> from);
private static readonly UnsafeRefCastDelegate _delegate;
private static readonly int _size;
static Unsafe()
{
var tFrom = typeof(Span<IntPtr>);
var tTo = typeof(T);
_size = Marshal.ReadInt32(ptr: tTo.TypeHandle.Value, ofs: 4);
var method = new DynamicMethod(
name: "UnsafeRefAs",
returnType: tTo.MakeByRefType(),
parameterTypes: [tFrom.MakeByRefType()],
m: typeof(Unsafe).Module,
skipVisibility: true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ret);
_delegate = (UnsafeRefCastDelegate)method.CreateDelegate(typeof(UnsafeRefCastDelegate));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T As(ref Span<IntPtr> source) => ref _delegate(ref source);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int SizeOf() => _size;
}