Skip to content

Instantly share code, notes, and snippets.

@kevingosse
Last active July 26, 2022 12:14
Show Gist options
  • Save kevingosse/94f6396e28fa6773b435e1adc882d537 to your computer and use it in GitHub Desktop.
Save kevingosse/94f6396e28fa6773b435e1adc882d537 to your computer and use it in GitHub Desktop.
public unsafe class Getter
{
private delegate*<Obj, SomeStruct> _functionPointer;
public Getter(string propName)
{
var methodInfo = typeof(Obj).GetProperty(propName).GetGetMethod();
_functionPointer = (delegate*<Obj, SomeStruct>)methodInfo.MethodHandle.GetFunctionPointer();
}
public SomeStruct GetFromFunctionPointer(Obj target)
{
var v = _functionPointer(target);
return v;
}
}
public struct SomeStruct
{
public int Value1;
public int Value2;
public int Value3;
public int Value4;
}
public class Obj
{
public SomeStruct Property { get; set; }
}
class Program
{
static void Main(string[] args)
{
var obj = new Obj { Property = new SomeStruct { Value1 = 42 } };
var getter = new Getter("Property");
Console.WriteLine($"Value: {getter.GetFromFunctionPointer(obj).Value1}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment