Last active
August 29, 2015 14:17
-
-
Save nickdarnell/82be3354b1e703c17158 to your computer and use it in GitHub Desktop.
This file contains 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
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