vendredi 1 avril 2016

Create / assign object via C# EMIT IL

new to IL... trying to create IL for:

Dest CreateInstance(Source src)
{
   Dest d = new Dest();
   d.Test = src.Test;
   return d;
}

This is what I have so far:

ConstructorInfo ctor = typeof(Dest).GetConstructors()[0];
DynamicMethod method = new DynamicMethod("CreateIntance", typeof(Dest),
    new Type[] { typeof(Source) });
ILGenerator gen = method.GetILGenerator();
//gen.Emit(OpCodes.Ldarg_0);// source
gen.Emit(OpCodes.Newobj, ctor);// new Created
gen.Emit(OpCodes.Ret);
CreateCtor createdCtorDelegate;
createdCtorDelegate = (CreateCtor)method.CreateDelegate(typeof(CreateCtor));

this runs as above... but if I uncomment out the Ldarg_0, I get a "this operation may unstabilize the runtime" when I try to call the delegate.

Also, what do I need to copy the Test member over? assuming its a basic type.

Thanks!





Aucun commentaire:

Enregistrer un commentaire