Reputation: 1193
Hi guys I am trying to generate a delegate at runtime using Dynamic Methods and the ILGenerator to invoke the Setter of a property on an object.....
private static GenericIntSetter CreateIntSetMethod(PropertyInfo propertyInfo)
{
MethodInfo setMethod = propertyInfo.GetSetMethod();
if (setMethod == null)
return null;
Type[] arguments = new Type[2];
arguments[0] = typeof(Person);
arguments[1] = typeof(int);
DynamicMethod setter = new DynamicMethod(
String.Concat("_Set", propertyInfo.Name, "_"),
typeof(void), arguments, propertyInfo.DeclaringType);
ILGenerator generator = setter.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
generator.Emit(OpCodes.Ldarg_1);
if (propertyInfo.PropertyType.IsClass)
{
generator.Emit(OpCodes.Castclass, propertyInfo.PropertyType);
}
else
{
generator.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
}
generator.EmitCall(OpCodes.Callvirt, setMethod, null);
generator.Emit(OpCodes.Ret);
return (GenericIntSetter)setter.CreateDelegate(typeof(GenericIntSetter));
}
When I call this method and I invoke the delete I get a corrupt memory error, any ideas?
Upvotes: 0
Views: 1720
Reputation: 8372
Yep. It's really complicated to do that, but not impossible.
I have a open source project just for that http://mirrormirror.codeplex.com
In http://mirrormirror.codeplex.com/SourceControl/changeset/view/66562#869731 you will find the code for all the emit I need to do. It should be easy to find the setter implementation.
Hope it helps
Upvotes: 1