本文整理汇总了C#中System.Reflection.Emit.DynamicMethod.GetILGenerator方法的典型用法代码示例。如果您正苦于以下问题:C# DynamicMethod.GetILGenerator方法的具体用法?C# DynamicMethod.GetILGenerator怎么用?C# DynamicMethod.GetILGenerator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Reflection.Emit.DynamicMethod
的用法示例。
在下文中一共展示了DynamicMethod.GetILGenerator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateGetField
internal static GenericGetter CreateGetField(Type type, FieldInfo fieldInfo)
{
DynamicMethod dynamicGet = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type);
ILGenerator il = dynamicGet.GetILGenerator();
if (!type.IsClass) // structs
{
var lv = il.DeclareLocal(type);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Unbox_Any, type);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloca_S, lv);
il.Emit(OpCodes.Ldfld, fieldInfo);
if (fieldInfo.FieldType.IsValueType)
il.Emit(OpCodes.Box, fieldInfo.FieldType);
}
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, fieldInfo);
if (fieldInfo.FieldType.IsValueType)
il.Emit(OpCodes.Box, fieldInfo.FieldType);
}
il.Emit(OpCodes.Ret);
return (GenericGetter)dynamicGet.CreateDelegate(typeof(GenericGetter));
}
示例2: DelegateFieldSetAccessor
/// <summary>
/// Initializes a new instance of the <see cref="DelegateFieldSetAccessor"/> class
/// for field get access via DynamicMethod.
/// </summary>
/// <param name="targetObjectType">Type of the target object.</param>
/// <param name="fieldName">Name of the field.</param>
public DelegateFieldSetAccessor(Type targetObjectType, string fieldName)
{
// this.targetType = targetObjectType;
_fieldName = fieldName;
FieldInfo fieldInfo = targetObjectType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
// Make sure the field exists
if (fieldInfo == null)
{
throw new NotSupportedException(
string.Format("Field \"{0}\" does not exist for type "
+ "{1}.", fieldName, targetObjectType));
}
_fieldType = fieldInfo.FieldType;
nullInternal = GetNullInternal(_fieldType);
// Emit the IL for set access.
DynamicMethod dynamicMethodSet = new DynamicMethod("SetImplementation", null, new Type[] { typeof(object), typeof(object) }, GetType().Module, false);
ILGenerator ilgen = dynamicMethodSet.GetILGenerator();
ilgen = dynamicMethodSet.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Ldarg_1);
UnboxIfNeeded(fieldInfo.FieldType, ilgen);
ilgen.Emit(OpCodes.Stfld, fieldInfo);
ilgen.Emit(OpCodes.Ret);
_set = (SetValue)dynamicMethodSet.CreateDelegate(typeof(SetValue));
}
示例3: GenerateDelegate
private static PropertyMapper GenerateDelegate(Type sourceType, Type targetType, bool ignoreMappings)
{
var method = new DynamicMethod("Map_" + sourceType.FullName + "_" + targetType.FullName, null, new[] { typeof(object), typeof(object) });
var il = method.GetILGenerator();
var sourceProperties = Reflector.GetAllProperties(sourceType);
var targetProperties = Reflector.GetAllProperties(targetType);
var entityMap = MappingFactory.GetEntityMap(targetType);
var matches = sourceProperties.CrossJoin(targetProperties).Where(t => t.Item2.Name == MappingFactory.GetPropertyOrColumnName(t.Item3, ignoreMappings, entityMap, false)
&& t.Item2.PropertyType == t.Item3.PropertyType
&& t.Item2.PropertyType.IsPublic
&& t.Item3.PropertyType.IsPublic
//&& (t.Item3.PropertyType.IsValueType || t.Item3.PropertyType == typeof(string))
&& t.Item2.CanRead && t.Item3.CanWrite);
foreach (var match in matches)
{
il.Emit(OpCodes.Ldarg_1);
il.EmitCastToReference(targetType);
il.Emit(OpCodes.Ldarg_0);
il.EmitCastToReference(sourceType);
il.Emit(OpCodes.Callvirt, match.Item2.GetGetMethod());
il.Emit(OpCodes.Callvirt, match.Item3.GetSetMethod());
}
il.Emit(OpCodes.Ret);
var mapper = (PropertyMapper)method.CreateDelegate(typeof(PropertyMapper));
return mapper;
}
示例4: CreateGetMethod
/// <summary>
/// Creates a dynamic getter for the property
/// </summary>
/// <param name="propertyInfo"></param>
/// <returns></returns>
public static GenericGetter CreateGetMethod(PropertyInfo propertyInfo)
{
/*
* If there's no getter return null
*/
MethodInfo getMethod = propertyInfo.GetGetMethod();
if (getMethod == null)
return null;
/*
* Create the dynamic method
*/
Type[] arguments = new Type[1];
arguments[0] = typeof(object);
DynamicMethod getter = new DynamicMethod(
String.Concat("_Get", propertyInfo.Name, "_"),
typeof(object), arguments, propertyInfo.DeclaringType,false);
ILGenerator generator = getter.GetILGenerator();
generator.DeclareLocal(typeof(object));
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
generator.EmitCall(OpCodes.Callvirt, getMethod, null);
if (!propertyInfo.PropertyType.IsClass)
generator.Emit(OpCodes.Box, propertyInfo.PropertyType);
generator.Emit(OpCodes.Ret);
/*
* Create the delegate and return it
*/
return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
}
示例5: GenerateMethodBody
private void GenerateMethodBody(DynamicMethod dynamicMethod) {
var ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0); // Load templateControl argument onto stack
ilGenerator.Emit(OpCodes.Ldarg_1); // Load virtualPath argument onto stack
ilGenerator.Emit(OpCodes.Call, invoker); // Invoke LoadControlInvoker with the loaded two arguments
ilGenerator.Emit(OpCodes.Ret); // End method
}
示例6: GetBindByName
static Action<IDbCommand, bool> GetBindByName(Type commandType)
{
if (commandType == null) return null; // GIGO
Action<IDbCommand, bool> action;
if (Link<Type, Action<IDbCommand, bool>>.TryGet(bindByNameCache, commandType, out action))
{
return action;
}
var prop = commandType.GetProperty("BindByName", BindingFlags.Public | BindingFlags.Instance);
action = null;
ParameterInfo[] indexers;
MethodInfo setter;
if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool)
&& ((indexers = prop.GetIndexParameters()) == null || indexers.Length == 0)
&& (setter = prop.GetSetMethod()) != null
)
{
var method = new DynamicMethod(commandType.Name + "_BindByName", null, new Type[] { typeof(IDbCommand), typeof(bool) });
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, commandType);
il.Emit(OpCodes.Ldarg_1);
il.EmitCall(OpCodes.Callvirt, setter, null);
il.Emit(OpCodes.Ret);
action = (Action<IDbCommand, bool>)method.CreateDelegate(typeof(Action<IDbCommand, bool>));
}
// cache it
Link<Type, Action<IDbCommand, bool>>.TryAdd(ref bindByNameCache, commandType, ref action);
return action;
}
示例7: BehaviorModel
public BehaviorModel()
{
var modelType = GetType();
if (!s_data.TryGetValue(modelType, out m_data))
{
lock (s_data)
{
if (!s_data.TryGetValue(modelType, out m_data))
{
m_data = new BehaviorModelData
{
BhvModelAttr = modelType.GetAttribute<BehaviorModelAttribute>()
};
var bhvType = m_data.BhvModelAttr != null
? m_data.BhvModelAttr.BehaviorType
: SupplementBehaviorType; // virtual function call to get the most derived value
var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + bhvType.FullName, bhvType, null, bhvType);
var ilGen = dynMethod.GetILGenerator();
ilGen.Emit(OpCodes.Newobj, bhvType.GetConstructor(Type.EmptyTypes));
ilGen.Emit(OpCodes.Ret);
m_data.BehaviorType = bhvType;
m_data.BhvFactory = (Func<IBehavior>)dynMethod.CreateDelegate(typeof(Func<IBehavior>));
m_data.IsBehaviorStatic = BehaviorModel.GetIsBehaviorStatic(bhvType);
s_data.Add(modelType, m_data);
}
}
}
m_name = null;
}
示例8: CreateFieldGetter
public static GetValueDelegate CreateFieldGetter(FieldInfo field)
{
if (field == null)
throw new ArgumentNullException("field");
DynamicMethod dm = new DynamicMethod("FieldGetter", typeof(object),
new Type[] { typeof(object) },
field.DeclaringType, true);
ILGenerator il = dm.GetILGenerator();
if (!field.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
EmitCastToReference(il, field.DeclaringType); //to handle struct object
il.Emit(OpCodes.Ldfld, field);
}
else
il.Emit(OpCodes.Ldsfld, field);
if (field.FieldType.IsValueType)
il.Emit(OpCodes.Box, field.FieldType);
il.Emit(OpCodes.Ret);
return (GetValueDelegate)dm.CreateDelegate(typeof(GetValueDelegate));
}
示例9: CreateGetInsertValues
internal static Func<object, SqlArgument[]> CreateGetInsertValues(IObjectInfo objectInfo)
{
var dynamicMethod = new DynamicMethod(
name: "MicroLite" + objectInfo.ForType.Name + "GetInsertValues",
returnType: typeof(SqlArgument[]),
parameterTypes: new[] { typeof(object) }, // arg_0
m: typeof(ObjectInfo).Module);
var ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.DeclareLocal(objectInfo.ForType); // loc_0 - {Type} instance;
ilGenerator.DeclareLocal(typeof(SqlArgument[])); // loc_1 - SqlArgument[] sqlArguments;
// instance = ({Type})arg_0;
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Castclass, objectInfo.ForType);
ilGenerator.Emit(OpCodes.Stloc_0);
// sqlArguments = new SqlArgument[count];
ilGenerator.EmitEfficientInt(objectInfo.TableInfo.InsertColumnCount);
ilGenerator.Emit(OpCodes.Newarr, typeof(SqlArgument));
ilGenerator.Emit(OpCodes.Stloc_1);
EmitGetPropertyValues(ilGenerator, objectInfo, c => c.AllowInsert);
// return sqlArguments;
ilGenerator.Emit(OpCodes.Ldloc_1);
ilGenerator.Emit(OpCodes.Ret);
var getInsertValues = (Func<object, SqlArgument[]>)dynamicMethod.CreateDelegate(typeof(Func<object, SqlArgument[]>));
return getInsertValues;
}
示例10: CreateGetMethod
private static DynamicGetter CreateGetMethod(PropertyInfo propertyInfo, Type type)
{
var getMethod = propertyInfo.GetGetMethod();
if (getMethod == null)
throw new InvalidOperationException(string.Format("Could not retrieve GetMethod for the {0} property of {1} type", propertyInfo.Name, type.FullName));
var arguments = new Type[1]
{
typeof (object)
};
var getterMethod = new DynamicMethod(string.Concat("_Get", propertyInfo.Name, "_"), typeof(object), arguments, propertyInfo.DeclaringType);
var generator = getterMethod.GetILGenerator();
generator.DeclareLocal(typeof(object));
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
generator.EmitCall(OpCodes.Callvirt, getMethod, null);
if (propertyInfo.PropertyType.IsClass == false)
generator.Emit(OpCodes.Box, propertyInfo.PropertyType);
generator.Emit(OpCodes.Ret);
return (DynamicGetter) getterMethod.CreateDelegate(typeof (DynamicGetter));
}
示例11: GetFiller
//todo: temporary public
public FillingDelegate GetFiller(TypeMappingInfo mapping, Table table)
{
var ct = typeof(object);
// Fill(reader, obj, offset)
Type[] methodArgs2 = { typeof(IDataRecord), ct, typeof(int) };
var method = new DynamicMethod(
"ct",
null,
methodArgs2, typeof(SqlValueMapper));
var generator = method.GetILGenerator();
Type type = mapping.Type;
var i = 0;
foreach(var prop in table.Columns)
{
var navigation = prop as NavigationPropertyMapping;
if (navigation != null)
{
GenerateForNavigationProperty(navigation, type, generator, i);
}
else
{
GenerateForPrimitive(type, prop, generator, i);
}
i++;
}
// return
generator.Emit(OpCodes.Ret);
return (FillingDelegate)method.CreateDelegate(typeof(FillingDelegate));
}
示例12: CreateCloneWrapper
private static CloneHandler CreateCloneWrapper(Type type)
{
var cloneMethod = new DynamicMethod
(
"NativeClone",
MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.NewSlot,
CallingConventions.Standard,
typeof(IntPtr), new Type[] { type },
type, false
);
var ilGenerator = cloneMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0); // Step 1: Push the object to clone on the stack
// Just to be clean, don't suppose ICloneable only has one member…
var cloneableInterfaceMap = type.GetInterfaceMap(typeof(ICloneable));
for (int i = 0; i < cloneableInterfaceMap.InterfaceMethods.Length; i++)
if (cloneableInterfaceMap.InterfaceMethods[i].Name == "Clone")
{
ilGenerator.Emit(OpCodes.Call, cloneableInterfaceMap.TargetMethods[i]); // Step 2: clone it
goto CloneMethodFound; // Finish the job once we found the Clone method (which should always be found)
}
throw new InvalidOperationException(); // This line should never be reached
CloneMethodFound:
ilGenerator.Emit(OpCodes.Isinst, type); // Step 3: Cast it to the correct type
var nativePointerProperty = type.GetProperty
(
"NativePointer",
BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder,
typeof(IntPtr), Type.EmptyTypes, null
);
ilGenerator.Emit(OpCodes.Call, nativePointerProperty.GetGetMethod(true)); // Step 4: Get the native pointer
ilGenerator.Emit(OpCodes.Ret); // Step 5: Return the value
return cloneMethod.CreateDelegate(typeof(CloneHandler)) as CloneHandler;
}
示例13: GetInstanceCreator
/// <summary>Gets the instance creator delegate that can be use to create instances of the specified type.</summary>
/// <param name="type">The type of the objects we want to create.</param>
/// <returns>A delegate that can be used to create the objects.</returns>
public static FastCreateInstanceHandler GetInstanceCreator(Type type)
{
lock (dictCreator)
{
if (dictCreator.ContainsKey(type)) return (FastCreateInstanceHandler)dictCreator[type];
// generates a dynamic method to generate a FastCreateInstanceHandler delegate
DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, type, new Type[0], typeof(DynamicCalls).Module);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
// generates code to create a new object of the specified type using the default constructor
ilGenerator.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));
// returns the value to the caller
ilGenerator.Emit(OpCodes.Ret);
// converts the DynamicMethod to a FastCreateInstanceHandler delegate to create the object
FastCreateInstanceHandler creator = (FastCreateInstanceHandler)dynamicMethod.CreateDelegate(typeof(FastCreateInstanceHandler));
dictCreator.Add(type, creator);
return creator;
}
}
示例14: TestCall2
public void TestCall2()
{
var parameters = new[] { typeof(int), typeof(int) };
var dm = new DynamicMethod("soma", typeof(int), parameters);
var gen = dm.GetILGenerator();
gen.DeclareLocal (typeof(Math));
var ctor = typeof(Math).GetConstructors () [0];
gen.Emit (OpCodes.Newobj, ctor);
gen.Emit (OpCodes.Stloc, 0);
gen.Emit (OpCodes.Ldobj, 0);
//gen.Emit(OpCodes.Ldarg_0);
//gen.Emit(OpCodes.Ldarg_1);
//var soma = GetType ().GetMethod ("Soma");
//gen.EmitCall (OpCodes.Callvirt, soma, new Type[] { });
gen.Emit (OpCodes.Ldc_I4, 2);
gen.Emit(OpCodes.Ret);
var result = dm.Invoke(null, new object[] { 1, 1 });
//var func = (Func<int, int, int>)dm.CreateDelegate(typeof(Func<int, int, int>));
Assert.AreEqual (2, result);
}
示例15: CreateCreateInstanceMethod
private static CreateInstanceInvoker CreateCreateInstanceMethod(Type type)
{
if (type.IsInterface || type.IsAbstract)
return null;
DynamicMethod method = new DynamicMethod(string.Empty, typeof (object), null, type, true);
ILGenerator il = method.GetILGenerator();
if (type.IsValueType)
{
LocalBuilder tmpLocal = il.DeclareLocal(type);
il.Emit(OpCodes.Ldloca, tmpLocal);
il.Emit(OpCodes.Initobj, type);
il.Emit(OpCodes.Ldloc, tmpLocal);
il.Emit(OpCodes.Box, type);
}
else
{
ConstructorInfo constructor = type.GetConstructor(AnyVisibilityInstance, null, CallingConventions.HasThis, NoClasses, null);
if (constructor == null)
throw new ApplicationException("Object class " + type + " must declare a default (no-argument) constructor");
il.Emit(OpCodes.Newobj, constructor);
}
il.Emit(OpCodes.Ret);
return (CreateInstanceInvoker) method.CreateDelegate(typeof (CreateInstanceInvoker));
}