Skip to content

Instantly share code, notes, and snippets.

View Sergio0694's full-sized avatar
🚀
Coding all day

Sergio Pedri Sergio0694

🚀
Coding all day
View GitHub Profile
public static void EmitAddOffset(this ILGenerator il, int offset)
{
// Push the offset to the stack
if (offset <= 8)
{
il.Emit(offset switch
{
0 => OpCodes.Ldc_I4_0,
1 => OpCodes.Ldc_I4_1,
2 => OpCodes.Ldc_I4_2,
public static void EmitStoreLocal(this ILGenerator il, int index)
{
if (index <= 3)
{
il.Emit(index switch
{
0 => OpCodes.Stloc_0,
1 => OpCodes.Stloc_1,
2 => OpCodes.Stloc_2,
3 => OpCodes.Stloc_3,
public static Func<object, object> BuildDynamicGetter(ClosureField field)
{
// Create a new dynamic method
FieldInfo[] hierarchy = field.Parents.Append(field.Info).ToArray();
Type ownerType = hierarchy[0].DeclaringType;
DynamicMethod method = new DynamicMethod(
$"Get{field.Info.Name}",
typeof(object), // The return type
new[] { typeof(object) }, // A single object parameter
ownerType); // The type that will own the new method
private static Func<object, object> BuildDynamicGetter(ClosureField field)
{
// Create a new dynamic method
Type ownerType = field.Info.DeclaringType;
DynamicMethod method = new DynamicMethod(
$"Get{field.Info.Name}",
typeof(object), // The return type
new [] { typeof(object) }, // A single object parameter
ownerType); // The type that will own the new method
// C#
public static int MultiplyAndAddOne(int a, int b)
{
int temp = a * b;
return temp + 1;
}
// IL (simplified)
public static int32 MultiplyAndAddOne(int32 a, int32 b)
{
# C#
public static object GetFieldXForVector2(object obj)
{
Vector2 instance = (Vector2)obj;
return instance.X;
}
# IL (simplified)
public static object GetFieldXForVector2(object obj)
{
public static unsafe (object[] References, byte[] Bytes) GetData(
Delegate instance, IReadOnlyList<ClosureField> fields)
{
// Calculate how many bytes we need
int
referenceCount = 0,
byteSize = 0;
foreach (var field in fields)
{
if (field.Info.FieldType.IsValueType)
public static void Main()
{
int[] array = new int[10];
{
int value = 1;
Action<int> action = i => array[i] = value;
foreach (var field in CollectFields(action))
{
public sealed class ClosureField
{
public FieldInfo Info { get; }
public IReadOnlyList<FieldInfo> Parents { get; }
public ClosureField(FieldInfo info, IReadOnlyList<FieldInfo> parents)
{
Info = info;
Parents = parents;
}
public static void Main()
{
int[] array = new int[10];
int value = 1;
Action<int> action = i => array[i] = value;
foreach (FieldInfo field in CollectFields(action))
{
Console.WriteLine($"{field.Name}: {field.GetValue(action.Target)}");