Here are the examples of the csharp api System.Reflection.Emit.DynamicMethod.GetILGenerator() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
538 Examples
19
Source : ReflectionFieldCache.cs
with MIT License
from cabarius
with MIT License
from cabarius
private Setter CreateSetter() {
DynamicMethod method = new(
name: "set_" + Info.Name,
returnType: null,
parameterTypes: new[] { Info.FieldType },
owner: typeof(CachedField<TField>),
skipVisibility: true);
method.DefineParameter(1, ParameterAttributes.In, "value");
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Stsfld, Info);
il.Emit(OpCodes.Ret);
return method.CreateDelegate(typeof(Setter)) as Setter;
}
19
Source : DynamicAsset.cs
with GNU General Public License v3.0
from cc004
with GNU General Public License v3.0
from cc004
public static Func<UnityBinaryReader, Dynamicreplacedet> GenDeserializer(TypeTree.Node[] nodes)
{
DynamicMethod dynamicMethod = new DynamicMethod(nodes[0].Type, typeof(Dynamicreplacedet), new Type[1]
{
typeof(UnityBinaryReader)
}, typeof(DynamicreplacedetArray).Module, skipVisibility: true);
new DeserializerBuilder(nodes).Build(dynamicMethod.GetILGenerator());
return (Func<UnityBinaryReader, Dynamicreplacedet>)dynamicMethod.CreateDelegate(typeof(Func<UnityBinaryReader, Dynamicreplacedet>));
}
19
Source : DynamicAsset.cs
with GNU General Public License v3.0
from cc004
with GNU General Public License v3.0
from cc004
public static Action<UnityBinaryWriter, Dynamicreplacedet> GenSerializer(TypeTree.Node[] nodes)
{
DynamicMethod dynamicMethod = new DynamicMethod(nodes[0].Type, null, new Type[2]
{
typeof(UnityBinaryWriter),
typeof(Dynamicreplacedet)
}, typeof(DynamicreplacedetArray).Module, skipVisibility: true);
new SerializerBuilder(nodes).Build(dynamicMethod.GetILGenerator());
return (Action<UnityBinaryWriter, Dynamicreplacedet>)dynamicMethod.CreateDelegate(typeof(Action<UnityBinaryWriter, Dynamicreplacedet>));
}
19
Source : DynamicAsset.Serializer.cs
with GNU General Public License v3.0
from cc004
with GNU General Public License v3.0
from cc004
public static Action<UnityBinaryWriter, Dynamicreplacedet> GenSerializer(TypeTree.Node[] nodes) {
DynamicMethod method = new DynamicMethod(nodes[0].Type, null, new Type[] { typeof(UnityBinaryWriter), typeof(Dynamicreplacedet) }, m: typeof(DynamicreplacedetArray).Module, skipVisibility: true);
SerializerBuilder builder = new SerializerBuilder(nodes);
builder.Build(method.GetILGenerator());
return (Action<UnityBinaryWriter, Dynamicreplacedet>)method.CreateDelegate(typeof(Action<UnityBinaryWriter, Dynamicreplacedet>));
}
19
Source : CompiledPacker.cs
with GNU Affero General Public License v3.0
from cc004
with GNU Affero General Public License v3.0
from cc004
private DynamicMethod CreatePacker(Type t, DynamicMethod dm)
{
ILGenerator iLGenerator = dm.GetILGenerator();
_packMethods.Add(t, dm);
PackILGenerator.EmitPackCode(t, dm, iLGenerator, LookupMembers, FormatMemberName, LookupPackMethod);
return dm;
}
19
Source : CompiledPacker.cs
with GNU Affero General Public License v3.0
from cc004
with GNU Affero General Public License v3.0
from cc004
private DynamicMethod CreateUnpacker(Type t, DynamicMethod dm)
{
ILGenerator iLGenerator = dm.GetILGenerator();
_unpackMethods.Add(t, dm);
PackILGenerator.EmitUnpackCode(t, dm, iLGenerator, LookupMembers, FormatMemberName, LookupUnpackMethod, LookupMemberMapping, LookupMemberMappingMethod);
return dm;
}
19
Source : DynamicAsset.Deserializer.cs
with GNU General Public License v3.0
from cc004
with GNU General Public License v3.0
from cc004
public static Func<UnityBinaryReader, Dynamicreplacedet> GenDeserializer(TypeTree.Node[] nodes) {
DynamicMethod method = new DynamicMethod(nodes[0].Type, typeof(Dynamicreplacedet), new Type[] { typeof(UnityBinaryReader) }, m: typeof(DynamicreplacedetArray).Module, skipVisibility: true);
DeserializerBuilder builder = new DeserializerBuilder(nodes);
builder.Build(method.GetILGenerator());
return (Func<UnityBinaryReader, Dynamicreplacedet>)method.CreateDelegate(typeof(Func<UnityBinaryReader, Dynamicreplacedet>));
}
19
Source : DynamicProxyHelper.cs
with MIT License
from ch00486259
with MIT License
from ch00486259
public static FastInvokeHandler CreateFastInvokeHandler(MethodInfo methodInfo)
{
DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object[]) }, methodInfo.DeclaringType.Module);
ILGenerator il = dynamicMethod.GetILGenerator();
ParameterInfo[] parameterArray = methodInfo.GetParameters();
Type[] parameterTypeArray = new Type[parameterArray.Length];
for (int i = 0; i < parameterTypeArray.Length; i++)
{
parameterTypeArray[i] = parameterArray[i].ParameterType;
}
LocalBuilder[] localBuilderArray = new LocalBuilder[parameterTypeArray.Length];
for (int i = 0; i < parameterTypeArray.Length; i++)
{
localBuilderArray[i] = il.DeclareLocal(parameterTypeArray[i], true);
}
for (int i = 0; i < parameterTypeArray.Length; i++)
{
var parameterType = parameterTypeArray[i];
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldelem_Ref);
if (parameterType.IsValueType)
{
il.Emit(OpCodes.Unbox_Any, parameterType);
}
else
{
il.Emit(OpCodes.Castclreplaced, parameterType);
}
il.Emit(OpCodes.Stloc, localBuilderArray[i]);
}
if (!methodInfo.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
}
for (int i = 0; i < parameterTypeArray.Length; i++)
{
il.Emit(OpCodes.Ldloc, localBuilderArray[i]);
}
if (methodInfo.IsStatic)
il.EmitCall(OpCodes.Call, methodInfo, null);
else
il.EmitCall(OpCodes.Callvirt, methodInfo, null);
if (methodInfo.ReturnType == typeof(void))
{
il.Emit(OpCodes.Ldnull);
}
else
{
if (methodInfo.ReturnType.IsValueType)
{
il.Emit(OpCodes.Box, methodInfo.ReturnType);
}
}
il.Emit(OpCodes.Ret);
var handler = (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler));
return handler;
}
19
Source : ObjectFactory.cs
with MIT License
from ch00486259
with MIT License
from ch00486259
private static Func<object> GetCreateFunc(Type type)
{
var ctor = type.GetConstructor(Type.EmptyTypes);
DynamicMethod method = new DynamicMethod(String.Empty, type, null);
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Ret);
return method.CreateDelegate(typeof(Func<object>)) as Func<object>;
}
19
Source : ObjectFactory.cs
with MIT License
from ch00486259
with MIT License
from ch00486259
public static Func<object[], object> CreateHandler(Type type, Type[] parameterTypeArray)
{
DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object[]) }, type.Module);
ILGenerator il = dynamicMethod.GetILGenerator();
ConstructorInfo constructorInfo = type.GetConstructor(parameterTypeArray);
if (constructorInfo == null)
throw new MissingMethodException("The constructor for the corresponding parameter was not found");
for (int i = 0; i < parameterTypeArray.Length; i++)
{
var parameterType = parameterTypeArray[i];
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldelem_Ref);
if (parameterType.IsValueType)
il.Emit(OpCodes.Unbox_Any, parameterType);
else
il.Emit(OpCodes.Castclreplaced, parameterType);
}
il.Emit(OpCodes.Newobj, constructorInfo);
il.Emit(OpCodes.Ret);
return (Func<object[], object>)dynamicMethod.CreateDelegate(typeof(Func<object[], object>));
}
19
Source : FieldAccessor.cs
with MIT License
from chequer-io
with MIT License
from chequer-io
protected override Getter CreateGetter(MemberInfo memberInfo)
{
var fieldInfo = (FieldInfo)memberInfo;
var method = new DynamicMethod(
$"{typeof(TType).Name}<{fieldInfo.Name}>_Getter",
typeof(TValue),
new[] { typeof(TType) }
);
var il = method.GetILGenerator();
il.DeclareLocal(typeof(TValue));
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, fieldInfo);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ret);
return method.CreateDelegate<Getter>();
}
19
Source : FieldAccessor.cs
with MIT License
from chequer-io
with MIT License
from chequer-io
protected override Setter CreateSetter(MemberInfo memberInfo)
{
var fieldInfo = (FieldInfo)memberInfo;
var method = new DynamicMethod(
$"{typeof(TType).Name}<{fieldInfo.Name}>_Setter",
typeof(void),
new[] { typeof(TType), typeof(TValue) }
);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, fieldInfo);
il.Emit(OpCodes.Ret);
return method.CreateDelegate<Setter>();
}
19
Source : PropertyAccessor.cs
with MIT License
from chequer-io
with MIT License
from chequer-io
protected override Getter CreateGetter(MemberInfo memberInfo)
{
var propertyInfo = (PropertyInfo)memberInfo;
if (propertyInfo.GetMethod == null)
return _ => throw new Exception("Getter not found.");
var method = new DynamicMethod(
$"{typeof(TType).Name}<{propertyInfo.Name}>_Getter",
typeof(TValue),
new[] { typeof(TType) }
);
var il = method.GetILGenerator();
il.DeclareLocal(typeof(TValue));
il.Emit(OpCodes.Nop);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, propertyInfo.GetMethod);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ret);
return method.CreateDelegate<Getter>();
}
19
Source : PropertyAccessor.cs
with MIT License
from chequer-io
with MIT License
from chequer-io
protected override Setter CreateSetter(MemberInfo memberInfo)
{
var propertyInfo = (PropertyInfo)memberInfo;
if (propertyInfo.SetMethod == null)
return (_, _) => throw new Exception("Setter not found.");
var method = new DynamicMethod(
$"{typeof(TType).Name}<{propertyInfo.Name}>_Setter",
typeof(void),
new[] { typeof(TType), typeof(TValue) }
);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Callvirt, propertyInfo.SetMethod);
il.Emit(OpCodes.Ret);
return method.CreateDelegate<Setter>();
}
19
Source : Utils.cs
with GNU General Public License v3.0
from chi-rei-den
with GNU General Public License v3.0
from chi-rei-den
public static List<ILInstruction> GetInstructions(MethodBase method)
{
var dummy = new DynamicMethod("Dummy", typeof(void), new Type[] { });
if (method.GetMethodBody() is null)
{
return null;
}
return MethodBodyReader.GetInstructions(dummy.GetILGenerator(), method);
}
19
Source : DictionaryEmit.cs
with MIT License
from cocosip
with MIT License
from cocosip
public static Func<Dictionary<string, string>, T> GetObjectFunc<T>() where T : clreplaced, new()
{
if (typeof(ICollection).GetTypeInfo().IsreplacedignableFrom(typeof(T)))
{
throw new NotSupportedException("Not support type: ICollection");
}
var type = typeof(T);
var properties = PropertyInfoUtil.GetProperties(type).Where(x => x.CanWrite && TypeUtil.IsPrimitiveExtended(x.PropertyType, true, true)).ToList();
DynamicMethod dynamicMethod = new DynamicMethod("DictionaryToObject", type,
new Type[] { typeof(Dictionary<string, string>) }, type, true)
{
InitLocals = false
};
ILGenerator il = dynamicMethod.GetILGenerator();
//结束标签
Label endLabel = il.DefineLabel();
//定义变量 var user=new User();他为第0个变量
LocalBuilder obj = il.DeclareLocal(type);
LocalBuilder value = il.DeclareLocal(typeof(string));
// ReSharper disable once replacedignNullToNotNullAttribute
il.Emit(OpCodes.Newobj, type.GetTypeInfo().GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Stloc, obj);
foreach (var property in properties)
{
Label endIfLabel = il.DefineLabel();
//判断是否包含key
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, property.Name);
il.Emit(OpCodes.Callvirt, DictionaryContainsKey);
var tmp0 = il.DeclareLocal(typeof(int));
il.Emit(OpCodes.Stloc, tmp0);
il.Emit(OpCodes.Ldloc, tmp0);
il.Emit(OpCodes.Brfalse_S, endIfLabel);
//是否为空判断
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, property.Name);
il.Emit(OpCodes.Callvirt, DictionaryGereplacedem);
il.Emit(OpCodes.Stloc, value);
il.Emit(OpCodes.Ldloc, value);
il.Emit(OpCodes.Call, StringNull);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq);
var tmp = il.DeclareLocal(typeof(int));
il.Emit(OpCodes.Stloc, tmp);
il.Emit(OpCodes.Ldloc, tmp);
il.Emit(OpCodes.Brfalse_S, endIfLabel);
il.Emit(OpCodes.Ldloc, obj);
il.Emit(OpCodes.Ldloc, value);
Parse(il, property.PropertyType);
il.Emit(OpCodes.Callvirt, property.GetSetMethod());
il.MarkLabel(endIfLabel);
}
var result = il.DeclareLocal(type);
il.Emit(OpCodes.Ldloc, obj);
il.Emit(OpCodes.Stloc_S, result);
il.Emit(OpCodes.Br_S, endLabel);
il.MarkLabel(endLabel);
il.Emit(OpCodes.Ldloc_S, result);
il.Emit(OpCodes.Ret);
if (!(dynamicMethod.CreateDelegate(typeof(Func<Dictionary<string, string>, T>)) is Func<Dictionary<string, string>, T> func))
{
throw new VerificationException();
}
return func;
}
19
Source : DictionaryEmit.cs
with MIT License
from cocosip
with MIT License
from cocosip
public static Func<T, Dictionary<string, string>> GetDictionaryFunc<T>()
{
if (typeof(ICollection).GetTypeInfo().IsreplacedignableFrom(typeof(T)))
{
throw new NotSupportedException("Not support type: ICollection");
}
var type = typeof(Dictionary<string, string>);
var properties = PropertyInfoUtil.GetProperties(typeof(T)).Where(x => x.CanRead && TypeUtil.IsPrimitiveExtended(x.PropertyType, true, true)).ToList();
DynamicMethod dynamicMethod = new DynamicMethod("ObjectToDictionary", type,
new Type[] { typeof(T) }, typeof(object), true)
{
InitLocals = true
};
ILGenerator il = dynamicMethod.GetILGenerator();
//结束标签
Label endLabel = il.DefineLabel();
//定义变量 var user=new User();他为第0个变量
LocalBuilder obj = il.DeclareLocal(type);
//定义了可空类型的变量集合
Dictionary<Type, LocalBuilder> valueDict = new Dictionary<Type, LocalBuilder>();
// ReSharper disable once replacedignNullToNotNullAttribute
il.Emit(OpCodes.Newobj, type.GetTypeInfo().GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Stloc, obj);
int index = 0;
foreach (var property in properties)
{
Label endIfLabel = il.DefineLabel();
//string,可空类型需要null判断
if (property.PropertyType == typeof(string))
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, property.GetGetMethod());
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Cgt_Un);
var tmp = il.DeclareLocal(typeof(bool));
il.Emit(OpCodes.Stloc, tmp);
il.Emit(OpCodes.Ldloc, tmp);
il.Emit(OpCodes.Brfalse_S, endIfLabel);
}
//可空类型
if (EmitUtil.IsNullable(property.PropertyType))
{
var hasValue = il.DeclareLocal(typeof(bool));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, property.GetGetMethod());
var local = GetLocal(il, property.PropertyType, valueDict);
il.Emit(OpCodes.Stloc_S, local);
il.Emit(OpCodes.Ldloca_S, local);
il.Emit(OpCodes.Call, property.PropertyType.GetTypeInfo().GetMethod("get_HasValue", new Type[] { }));
if (index == 0)
{
il.Emit(OpCodes.Stloc, hasValue);
il.Emit(OpCodes.Ldloc, hasValue);
}
else
{
il.Emit(OpCodes.Stloc_S, hasValue);
il.Emit(OpCodes.Ldloc_S, hasValue);
}
index++;
il.Emit(OpCodes.Brfalse_S, endIfLabel);
}
il.Emit(OpCodes.Ldloc, obj);
il.Emit(OpCodes.Ldstr, property.Name);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, property.GetGetMethod()); //取对象属性值
PropertyToString(il, property.PropertyType, valueDict);
il.Emit(OpCodes.Callvirt, DictionaryAddItem);
il.MarkLabel(endIfLabel);
}
var result = il.DeclareLocal(type);
il.Emit(OpCodes.Ldloc, obj);
il.Emit(OpCodes.Stloc_S, result);
il.Emit(OpCodes.Br_S, endLabel);
il.MarkLabel(endLabel);
il.Emit(OpCodes.Ldloc_S, result);
il.Emit(OpCodes.Ret);
if (!(dynamicMethod.CreateDelegate(typeof(Func<T, Dictionary<string, string>>)) is Func<T, Dictionary<string, string>> func))
{
throw new VerificationException();
}
return func;
}
19
Source : EmitHelper.cs
with Apache License 2.0
from Coldairarrow
with Apache License 2.0
from Coldairarrow
public static Func<object> CreateBuilder(Type type)
{
DynamicMethod dm = new DynamicMethod(string.Empty, typeof(object), Type.EmptyTypes);
var gen = dm.GetILGenerator();
if (type.IsValueType)
{
gen.DeclareLocal(type);
gen.Emit(OpCodes.Ldloca_S, 0);
gen.Emit(OpCodes.Initobj, type);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Box, type);
}
else
{
gen.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));
}
gen.Emit(OpCodes.Ret);
Func<object> func = (Func<object>)dm.CreateDelegate(typeof(Func<object>));
return func;
}
19
Source : DynamicReflectionDelegateFactory.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateMethodCallIL(method, generator);
return (MethodCall<T, object>)dynamicMethod.CreateDelegate(typeof(MethodCall<T, object>));
}
19
Source : DynamicReflectionDelegateFactory.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), Type.EmptyTypes, type);
dynamicMethod.InitLocals = true;
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateDefaultConstructorIL(type, generator);
return (Func<T>)dynamicMethod.CreateDelegate(typeof(Func<T>));
}
19
Source : DynamicReflectionDelegateFactory.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(T), new[] { typeof(object) }, propertyInfo.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateGetPropertyIL(propertyInfo, generator);
return (Func<T, object>)dynamicMethod.CreateDelegate(typeof(Func<T, object>));
}
19
Source : DynamicReflectionDelegateFactory.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateGetFieldIL(fieldInfo, generator);
return (Func<T, object>)dynamicMethod.CreateDelegate(typeof(Func<T, object>));
}
19
Source : DynamicReflectionDelegateFactory.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateSetFieldIL(fieldInfo, generator);
return (Action<T, object>)dynamicMethod.CreateDelegate(typeof(Action<T, object>));
}
19
Source : DynamicReflectionDelegateFactory.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType);
ILGenerator generator = dynamicMethod.GetILGenerator();
GenerateCreateSetPropertyIL(propertyInfo, generator);
return (Action<T, object>)dynamicMethod.CreateDelegate(typeof(Action<T, object>));
}
19
Source : JSON.cs
with MIT License
from CreateBrowser
with MIT License
from CreateBrowser
internal object FastCreateInstance(Type objtype)
{
try
{
CreateObject c = null;
if (_constrcache.TryGetValue(objtype, out c))
{
return c();
}
else
{
DynamicMethod dynMethod = new DynamicMethod("_",
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
typeof(object),
null,
objtype, false);
ILGenerator ilGen = dynMethod.GetILGenerator();
if (objtype.IsClreplaced)
{
ilGen.Emit(OpCodes.Newobj, objtype.GetConstructor(Type.EmptyTypes));
ilGen.Emit(OpCodes.Ret);
c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
_constrcache.Add(objtype, c);
}
else // structs
{
var lv = ilGen.DeclareLocal(objtype);
ilGen.Emit(OpCodes.Ldloca_S, lv);
ilGen.Emit(OpCodes.Initobj, objtype);
ilGen.Emit(OpCodes.Ldloc_0);
ilGen.Emit(OpCodes.Box, objtype);
ilGen.Emit(OpCodes.Ret);
c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
_constrcache.Add(objtype, c);
}
return c();
}
}
catch (Exception exc)
{
throw new Exception(string.Format("Failed to fast create instance for type '{0}' from replacedemebly '{1}'",
objtype.FullName, objtype.replacedemblyQualifiedName), exc);
}
}
19
Source : JSON.cs
with MIT License
from CreateBrowser
with MIT License
from CreateBrowser
internal static GenericSetter CreateSetField(Type type, FieldInfo fieldInfo)
{
Type[] arguments = new Type[2];
arguments[0] = arguments[1] = typeof(object);
DynamicMethod dynamicSet = new DynamicMethod("_", typeof(object), arguments, type, true);
ILGenerator il = dynamicSet.GetILGenerator();
if (!type.IsClreplaced) // 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.Ldarg_1);
if (fieldInfo.FieldType.IsClreplaced)
il.Emit(OpCodes.Castclreplaced, fieldInfo.FieldType);
else
il.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType);
il.Emit(OpCodes.Stfld, fieldInfo);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Box, type);
il.Emit(OpCodes.Ret);
}
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
if (fieldInfo.FieldType.IsValueType)
il.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType);
il.Emit(OpCodes.Stfld, fieldInfo);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ret);
}
return (GenericSetter)dynamicSet.CreateDelegate(typeof(GenericSetter));
}
19
Source : JSON.cs
with MIT License
from CreateBrowser
with MIT License
from CreateBrowser
internal static GenericSetter CreateSetMethod(Type type, PropertyInfo propertyInfo)
{
MethodInfo setMethod = propertyInfo.GetSetMethod();
if (setMethod == null)
return null;
Type[] arguments = new Type[2];
arguments[0] = arguments[1] = typeof(object);
DynamicMethod setter = new DynamicMethod("_", typeof(object), arguments, type);
ILGenerator il = setter.GetILGenerator();
if (!type.IsClreplaced) // 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.Ldarg_1);
if (propertyInfo.PropertyType.IsClreplaced)
il.Emit(OpCodes.Castclreplaced, propertyInfo.PropertyType);
else
il.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
il.EmitCall(OpCodes.Call, setMethod, null);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Box, type);
}
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclreplaced, propertyInfo.DeclaringType);
il.Emit(OpCodes.Ldarg_1);
if (propertyInfo.PropertyType.IsClreplaced)
il.Emit(OpCodes.Castclreplaced, propertyInfo.PropertyType);
else
il.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
il.EmitCall(OpCodes.Callvirt, setMethod, null);
il.Emit(OpCodes.Ldarg_0);
}
il.Emit(OpCodes.Ret);
return (GenericSetter)setter.CreateDelegate(typeof(GenericSetter));
}
19
Source : JSON.cs
with MIT License
from CreateBrowser
with MIT License
from CreateBrowser
internal static GenericGetter CreateGetField(Type type, FieldInfo fieldInfo)
{
DynamicMethod dynamicGet = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type, true);
ILGenerator il = dynamicGet.GetILGenerator();
if (!type.IsClreplaced) // 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));
}
19
Source : JSON.cs
with MIT License
from CreateBrowser
with MIT License
from CreateBrowser
internal static GenericGetter CreateGetMethod(Type type, PropertyInfo propertyInfo)
{
MethodInfo getMethod = propertyInfo.GetGetMethod();
if (getMethod == null)
return null;
Type[] arguments = new Type[1];
arguments[0] = typeof(object);
DynamicMethod getter = new DynamicMethod("_", typeof(object), arguments, type);
ILGenerator il = getter.GetILGenerator();
if (!type.IsClreplaced) // 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.EmitCall(OpCodes.Call, getMethod, null);
if (propertyInfo.PropertyType.IsValueType)
il.Emit(OpCodes.Box, propertyInfo.PropertyType);
}
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclreplaced, propertyInfo.DeclaringType);
il.EmitCall(OpCodes.Callvirt, getMethod, null);
if (propertyInfo.PropertyType.IsValueType)
il.Emit(OpCodes.Box, propertyInfo.PropertyType);
}
il.Emit(OpCodes.Ret);
return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
}
19
Source : ConfuserStringDecrypter.cs
with GNU General Public License v3.0
from CursedLand
with GNU General Public License v3.0
from CursedLand
object DynamicInvocation(MethodInfo method, string invokename, Module module, object[] mparams) {
var pT = new List<Type>();
foreach (ParameterInfo x in method.GetParameters())
pT.Add(x.ParameterType);
var dMethod = new DynamicMethod(invokename, typeof(string),
pT.ToArray(), module,
true);
var ILGen = dMethod.GetILGenerator();
for (int i = 0; i < mparams.Length; i++)
ILGen.Emit(OpCodes.Ldarg, i);
ILGen.Emit(OpCodes.Call, method);
ILGen.Emit(OpCodes.Ret);
return dMethod.Invoke(null, mparams);
}
19
Source : Program.cs
with MIT License
from dadhi
with MIT License
from dadhi
private static Func<object[], object> EmitDelegateFromExpression(Expression expr)
{
var method = new DynamicMethod("CreateA", typeof(object), new[] { typeof(object[]) });
var il = method.GetILGenerator();
var ok = EmittingVisitor.TryVisit(expr, il);
il.Emit(OpCodes.Ret);
return (Func<object[], object>)method.CreateDelegate(typeof(Func<object[], object>));
}
19
Source : ReflectionExtensions.cs
with MIT License
from dahall
with MIT License
from dahall
public static object InvokeNotOverride(this MethodInfo methodInfo, object targetObject, params object[] arguments)
{
var parameters = methodInfo.GetParameters();
if (parameters.Length != arguments.Length)
throw new Exception("Arguments count doesn't match");
Type returnType = null;
if (methodInfo.ReturnType != typeof(void))
returnType = methodInfo.ReturnType;
var type = targetObject.GetType();
var dynamicMethod = new DynamicMethod("", returnType, new[] { type, typeof(object) }, type);
var iLGenerator = dynamicMethod.GetILGenerator();
iLGenerator.Emit(OpCodes.Ldarg_0); // this
for (var i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
iLGenerator.Emit(OpCodes.Ldarg_1); // load array argument
// get element at index
iLGenerator.Emit(OpCodes.Ldc_I4_S, i); // specify index
iLGenerator.Emit(OpCodes.Ldelem_Ref); // get element
var parameterType = parameter.ParameterType;
iLGenerator.Emit(OpCodes.Unbox_Any, parameterType);
}
iLGenerator.Emit(OpCodes.Call, methodInfo);
iLGenerator.Emit(OpCodes.Ret);
return dynamicMethod.Invoke(null, new[] { targetObject, arguments });
}
19
Source : LateBinding.cs
with Apache License 2.0
from danielcrenna
with Apache License 2.0
from danielcrenna
public static Func<object, object> DynamicMethodBindGet(AccessorMember member)
{
var skipVisibility = member.Type.IsNotPublic;
var dm = new DynamicMethod($"{member.Name}", typeof(object), new[] {typeof(object)}, skipVisibility);
var il = dm.GetILGenerator();
switch (member.MemberInfo)
{
case PropertyInfo property:
{
var getMethod = property.GetGetMethod(true);
if (getMethod == null)
throw new ArgumentNullException();
il.Emit(OpCodes.Ldarg_0);
il.Emit(getMethod.IsFinal || !getMethod.IsVirtual ? OpCodes.Call : OpCodes.Callvirt, getMethod);
if (property.PropertyType.IsValueType)
il.Emit(OpCodes.Box, property.PropertyType);
break;
}
case FieldInfo field:
if (field.IsStatic)
il.Emit(OpCodes.Ldsfld, field);
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, field);
}
if (field.FieldType.IsValueType)
il.Emit(OpCodes.Box, field.FieldType);
break;
}
il.Emit(OpCodes.Ret);
return (Func<object, object>) dm.CreateDelegate(typeof(Func<object, object>));
}
19
Source : LateBinding.cs
with Apache License 2.0
from danielcrenna
with Apache License 2.0
from danielcrenna
public static Action<object, object> DynamicMethodBindSet(AccessorMember member)
{
var skipVisibility = member.Type.IsNotPublic;
var dm = new DynamicMethod($"{member.Name}", typeof(void), new[] {typeof(object), typeof(object)},
skipVisibility);
var il = dm.GetILGenerator();
Type memberType;
switch (member.MemberInfo)
{
case PropertyInfo property:
memberType = property.PropertyType;
break;
case FieldInfo field:
memberType = field.FieldType;
break;
default:
throw new ArgumentOutOfRangeException(nameof(member));
}
var declaringType = member.MemberInfo.DeclaringType;
il.Emit(OpCodes.Ldarg_0); // target
il.Emit(OpCodes.Castclreplaced, declaringType); // (Type)target
il.Emit(OpCodes.Ldarg_1); // value
il.Emit(OpCodes.Castclreplaced, memberType); // ({member.Type}) value
switch (member.MemberInfo)
{
case PropertyInfo property:
var setMethod = property.GetSetMethod(true);
il.Emit(setMethod.IsFinal || !setMethod.IsVirtual ? OpCodes.Call : OpCodes.Callvirt, setMethod);
break;
case FieldInfo field:
il.Emit(OpCodes.Stfld, field);
break;
default:
throw new ArgumentOutOfRangeException(nameof(member));
}
il.Emit(OpCodes.Ret);
return (Action<object, object>) dm.CreateDelegate(typeof(Action<object, object>));
}
19
Source : IlGeneratorExtensions.cs
with Apache License 2.0
from danielcrenna
with Apache License 2.0
from danielcrenna
public static ILSugar GetILGeneratorInternal(this DynamicMethod dm)
{
return new ILSugar(dm.GetILGenerator());
}
19
Source : StateProvider.cs
with Apache License 2.0
from danielcrenna
with Apache License 2.0
from danielcrenna
private static void PotentialMethodNameMatch(MethodTable methodTable, Type stateMachineType,
IDictionary<string, MethodInfo> stateMethods,
FieldInfo fieldInfo, MethodInfo methodInStateMachine, string potentialMethodName)
{
var methodInMethodTable = fieldInfo.FieldType.GetMethod("Invoke");
Debug.replacedert(methodInMethodTable != null, nameof(methodInMethodTable) + " != null");
if (methodInStateMachine.ReturnType != methodInMethodTable.ReturnType)
ThrowMethodMismatch(methodInStateMachine, methodInMethodTable);
var methodInMethodTableParameters = methodInMethodTable.GetParameters();
var methodInStateMachineParameters = methodInStateMachine.GetParameters();
if (methodInStateMachineParameters.Length != methodInMethodTableParameters.Length - 1
) // -1 to account for 'this' parameter to open delegate
ThrowMethodMismatch(methodInStateMachine, methodInMethodTable);
for (var i = 0; i < methodInStateMachineParameters.Length; i++)
if (methodInStateMachineParameters[i].ParameterType !=
methodInMethodTableParameters[i + 1]
.ParameterType && // +1 to account for 'this' parameter to open delegate
!methodInMethodTableParameters[i + 1].ParameterType
.IsreplacedignableFrom(methodInStateMachineParameters[i].ParameterType)
) // i.e. supports custom implementations of TStateData
ThrowMethodMismatch(methodInStateMachine, methodInMethodTable);
if (!stateMachineType.IsreplacedignableFrom(methodInMethodTableParameters[0].ParameterType))
{
Debug.replacedert(methodInMethodTableParameters[0].ParameterType.IsreplacedignableFrom(stateMachineType));
var dynamicMethod = new DynamicMethod($"CastingShim{Separator}{potentialMethodName}",
methodInMethodTable.ReturnType,
methodInMethodTableParameters.Select(pi => pi.ParameterType).ToArray(),
stateMachineType);
var il = dynamicMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclreplaced, stateMachineType); // <- the casting bit of the shim
if (methodInMethodTableParameters.Length > 1) il.Emit(OpCodes.Ldarg_1);
if (methodInMethodTableParameters.Length > 2) il.Emit(OpCodes.Ldarg_2);
if (methodInMethodTableParameters.Length > 3) il.Emit(OpCodes.Ldarg_3);
for (var i = 4; i < methodInMethodTableParameters.Length; i++)
if (i <= byte.MaxValue)
il.Emit(OpCodes.Ldarg_S, (byte) i);
else
il.Emit(OpCodes.Ldarg, (ushort) i);
il.Emit(OpCodes.Callvirt, methodInStateMachine);
il.Emit(OpCodes.Ret);
fieldInfo.SetValue(methodTable, dynamicMethod.CreateDelegate(fieldInfo.FieldType));
}
else
fieldInfo.SetValue(methodTable, Delegate.CreateDelegate(fieldInfo.FieldType, methodInStateMachine));
stateMethods.Remove(potentialMethodName);
}
19
Source : StateProvider.cs
with Apache License 2.0
from danielcrenna
with Apache License 2.0
from danielcrenna
private static void SetupStateMachineTypeRecursive(
IDictionary<Type, Dictionary<Type, State>> stateMachinesToStates,
IDictionary<Type, Dictionary<Type, MethodTable>> stateMachinesToAbstractStates,
Type stateMachineType)
{
Debug.replacedert(typeof(StateProvider).IsreplacedignableFrom(stateMachineType));
if (stateMachinesToStates.ContainsKey(stateMachineType)) return;
Dictionary<Type, State> baseStates = null;
Dictionary<Type, MethodTable> baseAbstractStates = null;
if (stateMachineType != typeof(StateProvider))
{
SetupStateMachineTypeRecursive(stateMachinesToStates, stateMachinesToAbstractStates,
stateMachineType.BaseType);
baseStates =
stateMachinesToStates[
stateMachineType.BaseType ??
throw new InvalidOperationException($"{nameof(MethodTable)} base type not found")];
baseAbstractStates = stateMachinesToAbstractStates[stateMachineType.BaseType];
}
const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance |
BindingFlags.DeclaredOnly;
var typeMethods = stateMachineType.GetMethods(bindingFlags);
var stateMethods = typeMethods.ToDictionary(mi => mi.Name);
var newStateTypes = stateMachineType.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)
.Where(nt => typeof(State).IsreplacedignableFrom(nt)).ToArray();
foreach (var newStateType in newStateTypes)
{
var newStateTypeMethods = newStateType.GetMethods(bindingFlags);
foreach (var newStateTypeMethod in newStateTypeMethods)
{
var methodName = GetFullyQualifiedStateMethodName(newStateTypeMethod);
if (stateMethods.ContainsKey(methodName))
{
var duplicateMethods = new List<string> {methodName};
if (methodName.StartsWith(StateDisambiguatorPrefix))
{
var naturalName = methodName.Replace(StateDisambiguatorPrefix, string.Empty);
if (stateMethods.ContainsKey(naturalName)) duplicateMethods.Add(naturalName);
}
throw new DuplicateStateMethodException(duplicateMethods.ToArray());
}
stateMethods.Add(methodName, newStateTypeMethod);
}
}
Type methodTableType;
var methodTableSearchType = stateMachineType;
while ((methodTableType =
methodTableSearchType?.GetNestedType(nameof(MethodTable),
BindingFlags.Public | BindingFlags.NonPublic)) == null)
{
if (!typeof(StateProvider).IsreplacedignableFrom(methodTableSearchType?.BaseType)) break;
methodTableSearchType = methodTableSearchType?.BaseType;
}
if (methodTableType == null)
throw new InvalidOperationException($"{nameof(MethodTable)} not found for {stateMachineType}");
if (!typeof(MethodTable).IsreplacedignableFrom(methodTableType))
throw new InvalidOperationException(
$"{nameof(MethodTable)} must be derived from StateMachine.MethodTable");
var states = new Dictionary<Type, State>();
var abstractStates = new Dictionary<Type, MethodTable>();
Debug.replacedert(baseStates != null == (baseAbstractStates != null));
if (baseStates != null)
{
foreach (var baseState in baseStates)
{
var state = (State) Activator.CreateInstance(baseState.Key);
state.methodTable =
ShallowCloneToDerived(baseState.Value.methodTable, methodTableType, stateMachineType);
FillMethodTableWithOverrides(baseState.Key, state.methodTable, stateMachineType, stateMethods);
states.Add(baseState.Key, state);
}
foreach (var baseAbstractState in baseAbstractStates)
{
var methodTable = ShallowCloneToDerived(baseAbstractState.Value, methodTableType, stateMachineType);
FillMethodTableWithOverrides(baseAbstractState.Key, methodTable, stateMachineType, stateMethods);
abstractStates.Add(baseAbstractState.Key, methodTable);
}
}
foreach (var stateType in newStateTypes)
SetupStateTypeRecursive(states, abstractStates, stateType, stateMachineType, methodTableType,
stateMethods);
var stateTypesToMethodTables = states
.Select(kvp => new KeyValuePair<Type, MethodTable>(kvp.Key, kvp.Value.methodTable))
.Concat(abstractStates).ToList();
foreach (var typeToMethodTable in stateTypesToMethodTables)
{
var methodTable = typeToMethodTable.Value;
var allMethodTableEntries = methodTable.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
.Where(fi => fi.FieldType.BaseType == typeof(MulticastDelegate)).ToList();
if (!allMethodTableEntries.Any()) stateMethods.Clear();
var toRemove = new List<string>(stateMethods.Keys);
foreach (var fieldInfo in allMethodTableEntries)
foreach (var stateMethod in stateMethods)
{
var ignore = stateMethod.Value.GetCustomAttributes(typeof(IgnoreStateMethodAttribute), false);
if (ignore.Length > 0) continue;
var aliasName = $@"{fieldInfo.Name}";
var disambiguatedName = $@"{StateDisambiguatorPrefix}_\w*_{fieldInfo.Name}";
var naturalName = $@"\w*_{fieldInfo.Name}";
if (Regex.IsMatch(stateMethod.Key, disambiguatedName) ||
Regex.IsMatch(stateMethod.Key, naturalName) ||
stateMethod.Key == aliasName)
toRemove.Remove(stateMethod.Key);
}
foreach (var stateMethod in toRemove) stateMethods.Remove(stateMethod);
}
if (stateMethods.Count > 0) throw new UnusedStateMethodsException(stateMethods.Values);
foreach (var typeToMethodTable in stateTypesToMethodTables)
{
var methodTable = typeToMethodTable.Value;
var allMethodTableEntries = methodTable.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)
.Where(fi => fi.FieldType.BaseType == typeof(MulticastDelegate));
foreach (var fieldInfo in allMethodTableEntries)
{
if (fieldInfo.GetCustomAttributes(typeof(AlwaysNullCheckedAttribute), true).Length != 0) continue;
if (fieldInfo.GetValue(methodTable) == null)
{
var methodInMethodTable = fieldInfo.FieldType.GetMethod("Invoke");
Debug.replacedert(methodInMethodTable != null, nameof(methodInMethodTable) + " != null");
var dynamicMethod = new DynamicMethod(
$"DoNothing{Separator}{GetStateName(typeToMethodTable.Key)}{Separator}{fieldInfo.Name}",
methodInMethodTable.ReturnType,
methodInMethodTable.GetParameters().Select(pi => pi.ParameterType).ToArray(),
stateMachineType);
var il = dynamicMethod.GetILGenerator();
EmitDefault(il, methodInMethodTable.ReturnType);
il.Emit(OpCodes.Ret);
fieldInfo.SetValue(methodTable, dynamicMethod.CreateDelegate(fieldInfo.FieldType));
}
}
}
stateMachinesToStates.Add(stateMachineType, states);
stateMachinesToAbstractStates.Add(stateMachineType, abstractStates);
}
19
Source : ActivationBenchmarks.cs
with Apache License 2.0
from danielcrenna
with Apache License 2.0
from danielcrenna
public static CreateInstanceNoParams DynamicMethodWeakTypedNoParams(ConstructorInfo ctor)
{
var dm = new DynamicMethod($"Construct_{ctor.MetadataToken}", ctor.DeclaringType, Type.EmptyTypes, true);
var il = dm.GetILGenerator();
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Ret);
return (CreateInstanceNoParams) dm.CreateDelegate(typeof(CreateInstanceNoParams));
}
19
Source : SnippetBenchmarks.cs
with Apache License 2.0
from danielcrenna
with Apache License 2.0
from danielcrenna
private static Func<int> CreateAnonymousMethod()
{
var dm = new DynamicMethod("__", typeof(int), Type.EmptyTypes);
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Ret);
return (Func<int>) dm.CreateDelegate(typeof(Func<int>));
}
19
Source : DirectAnonymousReadAccessor.cs
with Apache License 2.0
from danielcrenna
with Apache License 2.0
from danielcrenna
public Func<object, object> SimulateNonBranchingIndirectAccess(string fieldName)
{
var dm = new DynamicMethod("_", typeof(object), new[] {typeof(object)});
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldsfld, GetType().GetField(fieldName));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, GetType().GetField(fieldName).FieldType.GetMethod("Invoke"));
il.Emit(OpCodes.Ret);
var @delegate = (Func<object, object>) dm.CreateDelegate(typeof(Func<object, object>));
return @delegate;
}
19
Source : BaseEmitter.cs
with MIT License
from DaniilSokolyuk
with MIT License
from DaniilSokolyuk
internal Delegate GetDelegate()
{
var action = cache.Get( CallInfo );
if( action == null )
{
Method = CreateDynamicMethod();
Generator = new EmitHelper( Method.GetILGenerator() );
action = CreateDelegate();
cache.Insert( CallInfo, action, CacheStrategy.Temporary );
}
return action;
}
19
Source : MemberAccessor.cs
with Apache License 2.0
from Dasync
with Apache License 2.0
from Dasync
public static Delegate GetGetter(FieldInfo fieldInfo)
{
#warning This may not work with value types, also need to directly inject IL code in the ValueContainerTypeBuilder instead.
if (!fieldInfo.FieldType.IsPublic)
{
return (Func<object, object>)((obj) => fieldInfo.GetValue(obj));
}
else
{
return _fieldGetters.GetOrAdd(fieldInfo, fi =>
{
var getter = new DynamicMethod(GetGetterName(fi), fi.FieldType, new[] { typeof(object) }, true);
var getterIL = getter.GetILGenerator();
getterIL.Emit(OpCodes.Ldarg_0);
Type t;
getterIL.Emit(fi.DeclaringType.GetTypeInfo().IsValueType ? OpCodes.Unbox : OpCodes.Castclreplaced, fi.DeclaringType);
getterIL.Emit(OpCodes.Ldfld, fi);
getterIL.Emit(OpCodes.Ret);
return getter.CreateDelegate(typeof(Func<,>).MakeGenericType(typeof(object), fi.FieldType));
});
}
}
19
Source : MemberAccessor.cs
with Apache License 2.0
from Dasync
with Apache License 2.0
from Dasync
public static Delegate GetSetter(PropertyInfo propertyInfo)
{
if (!propertyInfo.PropertyType.IsPublic)
{
return (Action<object, object>)((obj, value) => propertyInfo.SetValue(obj, value));
}
else
{
return _propertySetters.GetOrAdd(propertyInfo, pi =>
{
if (!pi.CanWrite)
throw new InvalidOperationException(
$"Cannot create a setter method for non-writable property" +
$" '{pi.Name}' of type '{pi.DeclaringType.FullName}'.");
var setter = new DynamicMethod(GetSetterName(pi), typeof(void), new[] { typeof(object), pi.PropertyType }, true);
var setterIL = setter.GetILGenerator();
setterIL.Emit(OpCodes.Ldarg_0);
setterIL.Emit(pi.DeclaringType.GetTypeInfo().IsValueType ? OpCodes.Unbox : OpCodes.Castclreplaced, pi.DeclaringType);
setterIL.Emit(OpCodes.Ldarg_1);
setterIL.Emit(OpCodes.Call, pi.GetSetMethod(nonPublic: true));
setterIL.Emit(OpCodes.Ret);
return setter.CreateDelegate(typeof(Action<,>).MakeGenericType(typeof(object), pi.PropertyType));
});
}
}
19
Source : MemberAccessor.cs
with Apache License 2.0
from Dasync
with Apache License 2.0
from Dasync
public static Delegate GetGetter(PropertyInfo propertyInfo)
{
if (!propertyInfo.PropertyType.IsPublic)
{
return (Func<object, object>)((obj) => propertyInfo.GetValue(obj));
}
else
{
return _propertyGetters.GetOrAdd(propertyInfo, pi =>
{
if (!pi.CanRead)
throw new InvalidOperationException(
$"Cannot create a getter method for non-readable property" +
$" '{pi.Name}' of type '{pi.DeclaringType.FullName}'.");
var getter = new DynamicMethod(GetGetterName(pi), pi.PropertyType, new[] { typeof(object) }, true);
var getterIL = getter.GetILGenerator();
getterIL.Emit(OpCodes.Ldarg_0);
getterIL.Emit(pi.DeclaringType.GetTypeInfo().IsValueType ? OpCodes.Unbox : OpCodes.Castclreplaced, pi.DeclaringType);
getterIL.Emit(OpCodes.Call, pi.GetGetMethod(nonPublic: true));
getterIL.Emit(OpCodes.Ret);
return getter.CreateDelegate(typeof(Func<,>).MakeGenericType(typeof(object), pi.PropertyType));
});
}
}
19
Source : MethodInvoker.cs
with Apache License 2.0
from Dasync
with Apache License 2.0
from Dasync
private static DynamicMethod BuildInvokeMethod(
MethodInfo method,
IStronglyTypedValueContainer sampleContainer)
{
DynamicMethod dm;
if (method.DeclaringType.GetTypeInfo().IsInterface)
{
dm = new DynamicMethod(method.Name + "!d", method.ReturnType,
new Type[] { method.DeclaringType, typeof(IValueContainer) },
method.Module);
}
else
{
dm = new DynamicMethod(method.Name + "!d", method.ReturnType,
new Type[] { method.DeclaringType, typeof(IValueContainer) },
method.DeclaringType);
}
var il = dm.GetILGenerator();
var paramCount = sampleContainer.GetCount();
if (paramCount > 0)
{
il.DeclareLocal(sampleContainer.GetType());
il.Emit(OpCodes.Ldarg_1);
if (sampleContainer.GetType().GetTypeInfo().IsValueType)
{
il.Emit(OpCodes.Unbox_Any, sampleContainer.GetType());
}
else
{
il.Emit(OpCodes.Castclreplaced, sampleContainer.GetType());
}
il.Emit(OpCodes.Stloc_0);
}
if (!method.IsStatic)
il.Emit(OpCodes.Ldarg_0);
for (var i = 0; i < paramCount; i++)
{
var member = sampleContainer.GetMember(i);
if (member is FieldInfo fi)
{
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldfld, fi);
}
else if (member is PropertyInfo pi)
{
if (sampleContainer.GetType().GetTypeInfo().IsValueType)
{
il.Emit(OpCodes.Ldloca_S, 0);
}
else
{
il.Emit(OpCodes.Ldloc_0);
}
il.Emit(OpCodes.Call, pi.GetMethod);
}
else
{
throw new InvalidOperationException();
}
}
if (method.IsAbstract || method.DeclaringType.GetTypeInfo().IsInterface)
il.Emit(OpCodes.Callvirt, method);
else
il.Emit(OpCodes.Call, method);
il.Emit(OpCodes.Ret);
return dm;
}
19
Source : MemberAccessor.cs
with Apache License 2.0
from Dasync
with Apache License 2.0
from Dasync
public static Delegate GetSetter(FieldInfo fieldInfo)
{
if (!fieldInfo.FieldType.IsPublic)
{
return (Action<object, object>)((obj, value) => fieldInfo.SetValue(obj, value));
}
else
{
return _fieldSetters.GetOrAdd(fieldInfo, fi =>
{
var setter = new DynamicMethod(GetSetterName(fi), typeof(void), new[] { typeof(object), fi.FieldType }, true);
var setterIL = setter.GetILGenerator();
setterIL.Emit(OpCodes.Ldarg_0);
setterIL.Emit(fi.DeclaringType.GetTypeInfo().IsValueType ? OpCodes.Unbox : OpCodes.Castclreplaced, fi.DeclaringType);
setterIL.Emit(OpCodes.Ldarg_1);
setterIL.Emit(OpCodes.Stfld, fi);
setterIL.Emit(OpCodes.Ret);
return setter.CreateDelegate(typeof(Action<,>).MakeGenericType(typeof(object), fi.FieldType));
});
}
}
19
Source : DelegateHelper.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
private static TDelegateType InnerCreateGetMemberDelegate<TObject, TValue, TDelegateType>(string memberName)
where TDelegateType : clreplaced
{
Type type = typeof (TObject);
Type tValue = typeof (TValue);
var methodKey = new MethodCallDelegateKey(typeof (TDelegateType), memberName, type, tValue);
TDelegateType result = GetCachedDelegate(methodKey) as TDelegateType;
if (result==null)
lock (cachedDelegates.SyncRoot) {
result = GetCachedDelegate(methodKey) as TDelegateType;
if (result!=null)
return result;
PropertyInfo pi = type.GetProperty(memberName);
FieldInfo fi = type.GetField(memberName);
MethodInfo smi;
if (pi!=null) {
// Member is a Property...
MethodInfo mi = pi.GetGetMethod(true);
if (mi!=null) {
// Calling a property's get accessor is faster/cleaner using
// Delegate.CreateDelegate rather than Reflection.Emit
result = Delegate.CreateDelegate(typeof (TDelegateType), mi) as TDelegateType;
}
else
throw new InvalidOperationException(string.Format(Strings.ExPropertyDoesNotHaveGetter,
memberName, type.GetShortName()));
}
else if (fi!=null) {
// Member is a Field...
DynamicMethod dm = new DynamicMethod("Get" + memberName,
typeof (TValue), new Type[] {type}, type);
ILGenerator il = dm.GetILGenerator();
// Load the instance of the object (argument 0) onto the stack
il.Emit(OpCodes.Ldarg_0);
// Load the value of the object's field (fi) onto the stack
il.Emit(OpCodes.Ldfld, fi);
// return the value on the top of the stack
il.Emit(OpCodes.Ret);
result = dm.CreateDelegate(typeof (TDelegateType)) as TDelegateType;
}
else if (null!=(smi = type.GetMethod(AspectedPrivateFieldGetterPrefix + memberName,
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.ExactBinding))) {
result = Delegate.CreateDelegate(typeof (Func<TObject, TValue>), smi) as TDelegateType;
}
else
throw new InvalidOperationException(string.Format(Strings.ExMemberIsNotPublicPropertyOrField,
memberName, type.GetShortName()));
AddCachedDelegate(methodKey, result as Delegate);
}
return result;
}
19
Source : DelegateHelper.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
public static Action<TObject, TValue> CreateSetMemberDelegate<TObject, TValue>(string memberName)
{
Type type = typeof (TObject);
Type tValue = typeof (TValue);
var methodKey = new MethodCallDelegateKey(memberName, type, tValue);
Action<TObject, TValue> result = (Action<TObject, TValue>)GetCachedDelegate(methodKey);
if (result==null)
lock (cachedDelegates.SyncRoot) {
result = (Action<TObject, TValue>)GetCachedDelegate(methodKey);
if (result!=null)
return result;
PropertyInfo pi = type.GetProperty(memberName);
FieldInfo fi = type.GetField(memberName);
if (pi!=null) {
// Member is a Property...
MethodInfo mi = pi.GetSetMethod(true);
if (mi!=null) {
// Calling a property's get accessor is faster/cleaner using
// Delegate.CreateDelegate rather than Reflection.Emit
// TODO: Check that type conversion is adequate.
result = (Action<TObject, TValue>)Delegate.CreateDelegate(typeof (Action<TObject, TValue>), mi);
}
else
throw new InvalidOperationException(string.Format(Strings.ExPropertyDoesNotHaveSetter,
memberName, type.GetShortName()));
}
else if (fi!=null) {
// Member is a Field...
DynamicMethod dm = new DynamicMethod("Set" + memberName,
typeof (TValue), new Type[] {type}, type);
ILGenerator il = dm.GetILGenerator();
// Load the instance of the object (argument 0) onto the stack
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
// Load the value of the object's field (fi) onto the stack
il.Emit(OpCodes.Stfld, fi);
// return the value on the top of the stack
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Ret);
result = (Action<TObject, TValue>)dm.CreateDelegate(typeof (Func<TObject, TValue>));
}
else
throw new InvalidOperationException(string.Format(Strings.ExMemberIsNotPublicPropertyOrField,
memberName, type.GetShortName()));
AddCachedDelegate(methodKey, result);
}
return result;
}
19
Source : DelegateHelper.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
public static Converter<TSource, TTarget> CreatePrimitiveCastDelegate<TSource, TTarget>()
where TSource: struct
where TTarget: struct
{
Type sourceType = typeof (TSource);
Type targetType = typeof (TTarget);
string methodName = $"{primitiveCastMethodName}_{sourceType}_{targetType}";
var methodKey = new MethodCallDelegateKey(methodName);
var result = GetCachedDelegate(methodKey) as Converter<TSource, TTarget>;
if (result==null)
lock (cachedDelegates.SyncRoot) {
result = GetCachedDelegate(methodKey) as Converter<TSource, TTarget>;
if (result!=null)
return result;
Type actualSourceType = sourceType;
if (sourceType.IsEnum)
actualSourceType = Enum.GetUnderlyingType(sourceType);
if (!opCodeConv.ContainsKey(actualSourceType))
throw new InvalidCastException(string.Format(Strings.ExInvalidCast,
sourceType.GetShortName(),
targetType.GetShortName()));
Type actualTargetType = targetType;
if (targetType.IsEnum)
actualTargetType = Enum.GetUnderlyingType(targetType);
if (!opCodeConv.ContainsKey(actualTargetType))
throw new InvalidCastException(string.Format(Strings.ExInvalidCast,
sourceType.GetShortName(),
targetType.GetShortName()));
DynamicMethod dm = new DynamicMethod(methodName,
typeof(TTarget), new Type[] {sourceType});
ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
if (targetType.IsEnum)
if (typeOnStack[actualSourceType]!=typeOnStack[actualSourceType])
il.Emit(opCodeConv[actualTargetType]);
il.Emit(OpCodes.Ret);
result = dm.CreateDelegate(typeof(Converter<TSource, TTarget>)) as Converter<TSource, TTarget>;
AddCachedDelegate(methodKey, result);
}
return result;
}
19
Source : AstBuilder.cs
with MIT License
from daxnet
with MIT License
from daxnet
private DefaultAstNodeCreator CompileDefaultNodeCreator(Type nodeType) {
ConstructorInfo constr = nodeType.GetConstructor(Type.EmptyTypes);
DynamicMethod method = new DynamicMethod("CreateAstNode", nodeType, Type.EmptyTypes);
ILGenerator il = method.GetILGenerator();
il.Emit(OpCodes.Newobj, constr);
il.Emit(OpCodes.Ret);
var result = (DefaultAstNodeCreator) method.CreateDelegate(typeof(DefaultAstNodeCreator));
return result;
}
See More Examples