通过C#EMIT IL创建/分配对象



IL新手…正在尝试为创建IL

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

这就是我目前所拥有的:

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));

如上所述。。。但是,如果我取消对Ldarg_0的注释,当我尝试调用委托时,我会得到一个"此操作可能会使运行时不稳定"。

此外,我需要什么来复制测试成员?假设它是一种基本类型。

谢谢!

编辑:

来源和目的地以及简单的POCO。

public class Source
{
    public string S1 { get; set; }
    public string S2 { get; set; }
    public int I1 { get; set; }
    public int I2 { get; set; }
    public string S3 { get; set; }
    public string S4 { get; set; }
    public string S5 { get; set; }
}
public class Dest
{
    public string S1 { get; set; }
    public string S2 { get; set; }
    public int I1 { get; set; }
    public int I2 { get; set; }
    public string S3 { get; set; }
    public string S4 { get; set; }
    public string S5 { get; set; }
}

编辑#2:现在,我有这个。。。仍然得到去小型化错误:

        ConstructorInfo ctor = typeof(Dest).GetConstructors()[0];
        DynamicMethod method = new DynamicMethod("CreateIntance", typeof(Dest),
            new Type[] { typeof(Source) });
        MethodInfo miSrc = tSource.GetProperty("S1").GetGetMethod();
        MethodInfo miDest = tDest.GetProperty("S1").GetSetMethod();
        ILGenerator gen = method.GetILGenerator();
        gen.Emit(OpCodes.Newobj, ctor);// new Created
        gen.Emit(OpCodes.Dup);
        gen.Emit(OpCodes.Ldarg_1);// source
        gen.Emit(OpCodes.Ldfld, miSrc);
        gen.Emit(OpCodes.Stfld, miDest);
        gen.Emit(OpCodes.Ret);
        CreateCtor createdCtorDelegate;
        createdCtorDelegate = (CreateCtor)method.CreateDelegate(typeof(CreateCtor));
        Dest dd = createdCtorDelegate(s);

在调用createdCtorDelegate时获取异常。

第3版:

ILSpy显示:

.method public hidebysig static 
    class ConsoleApplication3.Dest Test (
        class ConsoleApplication3.Source s
    ) cil managed 
{
    // Method begins at RVA 0x2148
    // Code size 26 (0x1a)
    .maxstack 2
    .locals init (
        [0] class ConsoleApplication3.Dest,
        [1] class ConsoleApplication3.Dest
    )
IL_0000: nop
IL_0001: newobj instance void ConsoleApplication3.Dest::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldarg.0
IL_0009: callvirt instance string ConsoleApplication3.Source::get_S1()
IL_000e: callvirt instance void ConsoleApplication3.Dest::set_S1(string)
IL_0013: nop
IL_0014: ldloc.0
IL_0015: stloc.1
IL_0016: br.s IL_0018
IL_0018: ldloc.1
IL_0019: ret
} // end of method Program::Test

所以,我已经将我的代码调整为:

        ConstructorInfo ctor = typeof(Dest).GetConstructors()[0];
        DynamicMethod method = new DynamicMethod("CreateIntance", typeof(Dest),
            new Type[] { typeof(Source) });
        MethodInfo miSrc = tSource.GetProperty("S1").GetGetMethod();
        MethodInfo miDest = tDest.GetProperty("S1").GetSetMethod();
        ILGenerator gen = method.GetILGenerator();
        gen.Emit(OpCodes.Newobj, ctor);// new Created
        gen.Emit(OpCodes.Stloc_0);
        gen.Emit(OpCodes.Ldloc_0);
        gen.Emit(OpCodes.Ldarg_0);
        gen.Emit(OpCodes.Callvirt, miSrc);
        gen.Emit(OpCodes.Callvirt, miDest);
        gen.Emit(OpCodes.Ldloc_0);
        gen.Emit(OpCodes.Stloc_1);
        gen.Emit(OpCodes.Ldloc_1);
        gen.Emit(OpCodes.Ret);
        CreateCtor createdCtorDelegate;
        createdCtorDelegate = (CreateCtor)method.CreateDelegate(typeof(CreateCtor));

仍在崩溃:(…

但是如果我取消对Ldarg_0的注释。。。

方法应该返回一个值,这意味着当到达ret指令时,堆栈必须只包含一个项。newobj指令将创建新对象,并将对它的引用加载到堆栈中,因此,如果在到达ret之前向堆栈中添加更多项而不使用它们,则代码无效。

我需要复制测试成员什么?

获得有效IL指令的最快方法是使用高级语言以及编译器和反编译器。当你这样做的时候,你会得到这样的东西:

IL_0000: newobj instance void Dest::.ctor() //create the new object
IL_0005: dup                                //duplicate the reference
IL_0006: ldarg.1                            //load the object to copy from
IL_0007: ldfld object Source::Test          //load the value from the old objects field
IL_000c: stfld object Dest::Test            //safe the value to the new objects field
IL_0011: ret                                //one reference of the new object is still on the stack

您的最后一个代码接近正确,您只需要声明您想要使用的本地代码:

ILGenerator gen = method.GetILGenerator();
gen.DeclareLocal(typeof(Dest));

还要注意,末尾的最后一对stloc.1ldloc.1是不必要的,并且是在调试模式下编译代码的结果。检查CIL时,请始终在Release中编译代码,因为代码要短得多,更容易阅读。

你的第二个版本的方法也几乎是正确的,问题就在这里:

gen.Emit(OpCodes.Ldarg_1);// source

没有"参数1",因为参数列表从0开始(对于静态方法,实例方法的参数0为this)。修复方法很简单:

gen.Emit(OpCodes.Ldarg_0);// source

最新更新