c# - 为什么 Mono.Cecil 争论方法导入而我已经这样做了?

标签 c# roslyn cil il mono.cecil

这是我的代码:

    private void ModifyMethods()
    {
        SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
using System;

namespace ToIL
{
    public class Class1
    {
        public void Write()
        {
            Console.WriteLine(""Hello"");
        }
    }
}");


        string assemblyName = System.IO.Path.GetRandomFileName();
        MetadataReference[] references = new MetadataReference[]
        {
            MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
            MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
        };

        CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references,
            options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));


        Mono.Cecil.AssemblyDefinition asm = null;
        using (var ms = new MemoryStream())
        {
            var emitResult = compilation.Emit(ms);
            if (emitResult.Success)
            {
                ms.Seek(0, SeekOrigin.Begin);
                asm = Mono.Cecil.AssemblyDefinition.ReadAssembly(ms); 
            }
        }


        var class1 = asm.MainModule.Assembly.MainModule.Types.FirstOrDefault(T => T.Name == "Class1");
        var Method1 = class1.Methods.FirstOrDefault(M => M.Name == "Write");
        var ils = Method1.Body.Instructions;


        System.Reflection.MethodInfo mWriteLine = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
        Mono.Cecil.AssemblyDefinition asmx = Mono.Cecil.AssemblyDefinition.ReadAssembly(@"EditAsm.exe");
        var import = asmx.MainModule.Import(mWriteLine);
        foreach (var type in asmx.MainModule.Types)
        {
            if (type.Name == "<Module>") continue;
            foreach (var method in type.Methods)
            {
                var cilWorker = method.Body.GetILProcessor();
                foreach (var il in ils) cilWorker.Append(il);
            }
        }

        asmx.Write(@"d:\test.dll"); // Import Exception

    }

这段代码所做的是在程序集ToILClass1 中编译Write 方法。然后将方法体的IL(Instructions)存放在ils中。最后将指令添加到 EditAsm.exe 程序集的每个方法中。
正如所提供的那样,我已经导入了 WriteLine 但仍然在 asmx.Write(@"d:\test.dll");

处出现以下异常

成员 'System.Void System.Console::WriteLine(System.String)' 在另一个模块中声明,需要导入

最佳答案

那是因为您的 IL 指令属于另一个模块,因此其中的方法引用对于您将它们添加到的模块无效。 Import 实际上只是创建了对外部方法(字段等)的引用,但此引用对特定模块有效。您所有的 IL 指令方法调用操作数都有属于您代码中名为“assemblyName”的模块的引用。这一行:

var import = asmx.MainModule.Import(mWriteLine);

实际上什么都不做,因为你没有使用返回值。如何使用它(一般情况下)?像这样:

cilWorker.Append(Instruction.Create(OpCodes.Call, import));

您会看到,创建方法调用指令需要您要向其添加指令的特定模块的方法引用。现在,解决问题的可能方法:

foreach (var type in asmx.MainModule.Types) {
      if (type.Name == "<Module>") continue;
      foreach (var method in type.Methods) {
          var cilWorker = method.Body.GetILProcessor();
          foreach (var il in ils) {
              // grab method reference
              var methodRef = il.Operand as Mono.Cecil.MethodReference;
              if (methodRef != null) {
                  // if it belongs to another module
                  if (methodRef.Module.Name == (assemblyName + ".dll")) {
                      // resolve it back to method definition and then import, 
                      // now to the correct module. Assign result back to opcode operand
                      il.Operand = asmx.MainModule.Import(methodRef.Resolve());
                  }
              }

              cilWorker.Append(il);
          }
      }
  }

那么你的代码将不再抛出。

关于c# - 为什么 Mono.Cecil 争论方法导入而我已经这样做了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32666075/

相关文章:

.net - 有没有工具可以将 CIL 编译成二进制文件?

c# - Entity Framework 4 多对多不删除实际实体

c# - 简单注入(inject)器从命名空间注册所有服务

.net - 有没有办法使用 Roslyn 确定变量的潜在值?

c# - 如何使用 roslyn 获取项目的默认命名空间?

c++-cli - VS2015 C++/CLI Release Build 中的 NullReferenceException

C# IL 代码修改 - 保持堆栈完整

c# - 如何使用 youtube API V3 (c#) 安排 youtube 视频

c# - 如何在IdentityServer4/Identity中配置角色声明名称

c# - 无法编译 Roslyn 项目