I'm using Mono Cecil to create a new assembly at runtime. When calling the public static MyMethod() method on the created assembly if does not return anything, but the contructor of the new assembly type does output to the console. Any idea what I'm doing wrong here since there is no output from calling MyMethod() in my created assembly? There are no errors when I call the newly created static, I expected "New Result!" after "Loaded" and before the two "Do Something".
using System;
using System.Linq;
using System.Reflection;
using Mono.Cecil;
using Mono.Cecil.Cil;
using MyLib;
namespace MonoCecil_Test
{
class Program
{
static void Main(string[] args)
{
var assembly1 = AssemblyDefinition.ReadAssembly("MyLib.dll");
TypeDefinition type1 = assembly1.MainModule.Types.Single(x => x.Name == "TestClass");
MethodDefinition foundMethod = type1.Methods
.OfType<MethodDefinition>().Single(m => m.Name == "MyMethod" && m.Parameters.Count == 0);
ILProcessor worker = foundMethod.Body.GetILProcessor();
foundMethod.Body.Instructions.Clear();
Instruction ins1 = worker.Create(OpCodes.Ldstr, "New Result!");
Instruction ins2 = worker.Create(OpCodes.Ret);
worker.Append(ins1);
worker.Append(ins2);
assembly1.Write("Test.MyLib.dll");
Assembly assembly2 = Assembly.LoadFrom("Test.MyLib.dll");
Type type2 = assembly2.GetType("MyLib.TestClass");
object instanceOfMyType = Activator.CreateInstance(type2);
// Mock public static
MethodInfo method = type2.GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Static);
method.Invoke(null, null);
// Normal call
string result = TestClass.MyMethod();
Console.WriteLine(result);
Console.ReadKey();
}
}
}
MyLib.dll:
using System;
namespace MyLib
{
public class TestClass
{
public TestClass()
{
Console.WriteLine("Loaded");
}
public static string MyMethod()
{
string result = "Do Something";
Console.WriteLine(result);
return result;
}
}
}
Output is:
Loaded
Do Something
Do Something
Aucun commentaire:
Enregistrer un commentaire