Skip to content

Instantly share code, notes, and snippets.

@nickdarnell
Last active August 29, 2015 14:17
Show Gist options
  • Save nickdarnell/82be3354b1e703c17158 to your computer and use it in GitHub Desktop.
Save nickdarnell/82be3354b1e703c17158 to your computer and use it in GitHub Desktop.
private static Dictionary<Type, Func<IntPtr, bool, object>> constructorCache =
new Dictionary<Type, Func<IntPtr, bool, object>>();
private static Func<IntPtr, bool, object> CreateConstructorDelegate<T>()
{
// We need to first grab the reflection information for the more derrived type we're casting to.
// SWIG has protected constructors we'll be able to call that take 2 parameters, the native pointer
// to the type and whether or not SWIG owns the memory
ConstructorInfo ctor = typeof(T).GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic, null,
CallingConventions.HasThis, new Type[] { typeof(IntPtr), typeof(bool) }, null);
// Lets emit some IL that will allow us to construct our type much
// faster than using reflection.
DynamicMethod dm = new DynamicMethod("Create", typeof(object),
new Type[] { typeof(IntPtr), typeof(bool) }, typeof(T), true);
ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Ret);
// Create the delegate for the dynamic method, which will further improve the calling speed.
return (Func<IntPtr, bool, object>)dm.CreateDelegate(typeof(Func<IntPtr, bool, object>));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment