Created
September 17, 2013 16:53
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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