Skip to content

Instantly share code, notes, and snippets.

@kevingosse
Created July 26, 2022 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevingosse/830bdbae7f079895ec370eb65f36097e to your computer and use it in GitHub Desktop.
Save kevingosse/830bdbae7f079895ec370eb65f36097e to your computer and use it in GitHub Desktop.
public unsafe class Getter
{
private delegate*<Obj, SomeStruct*, SomeStruct*> _functionPointer;
public Getter(string propName)
{
var methodInfo = typeof(Obj).GetProperty(propName).GetGetMethod();
_functionPointer = (delegate*<Obj, SomeStruct*, SomeStruct*>)methodInfo.MethodHandle.GetFunctionPointer();
}
public SomeStruct GetFromFunctionPointer(Obj target)
{
// Allocate some space on the stack for the return value
SomeStruct returnValue = default;
var v = _functionPointer(target, &returnValue);
// We get a pointer to the return value. Dereference it to return the actual value to the caller
return *v;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment