【发布时间】:2015-09-19 08:34:18
【问题描述】:
这是我的代码:
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
}
这段代码的作用是在程序集ToIL 的Class1 内编译Write 方法。然后方法体的 IL(Instructions) 存储在ils 中。最后将指令添加到 EditAsm.exe 程序集的每个方法中。
正如所提供的那样,我已经导入了 WriteLine 但仍然在asmx.Write(@"d:\test.dll"); 得到以下异常
Member 'System.Void System.Console::WriteLine(System.String)' is declared in another module and needs to be imported
【问题讨论】:
标签: c# roslyn cil il mono.cecil