Skip to content

Instantly share code, notes, and snippets.

@cameronism
Created September 17, 2013 16:53
Show Gist options
  • Select an option

  • Save cameronism/6597158 to your computer and use it in GitHub Desktop.

Select an option

Save cameronism/6597158 to your computer and use it in GitHub Desktop.
Generate delegate to get pointer to fixed buffer field of a struct. Use with extreme caution: http://msdn.microsoft.com/en-us/library/zycewsya.aspx
public unsafe static class FieldPointer
{
public delegate void Get<TItem, TPtr>(ref TItem item, out TPtr* ptr)
where TItem : struct;
public static Get<TItem, TPtr> Generate<TItem, TPtr>(FieldInfo field)
where TItem : struct
{
var fixedElementField = field.FieldType.GetField("FixedElementField");
var dm = new DynamicMethod(
String.Format("GetFieldPointer_{0}_{1}", typeof(TItem).Name, field.Name),
typeof(void),
new[] { typeof(TItem).MakeByRefType(), typeof(TPtr).MakePointerType().MakeByRefType() },
typeof(FieldPointer).Module,
true);
var il = dm.GetILGenerator();
// push for later - used with Stind_I
il.Emit(OpCodes.Ldarg_1);
// push the instance, get the field address(es)
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldflda, field);
il.Emit(OpCodes.Ldflda, fixedElementField);
// convert address
il.Emit(OpCodes.Conv_I);
// store in arg_1
il.Emit(OpCodes.Stind_I);
// return
il.Emit(OpCodes.Ret);
return (Get<TItem, TPtr>)dm.CreateDelegate(typeof(Get<TItem, TPtr>));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment