12

I'm trying to write IL that calls methods in mscorlib, but I can't figure out how to get a ModuleDefinition to mscorlib to actually reference the types & methods, and documentation & google are lacking.

thecoop
  • 45,220
  • 19
  • 132
  • 189

1 Answers1

11

Getting a ModuleDefinition for the mscorlib is pretty easy. Here's a simple way:

ModuleDefinition corlib = ModuleDefinition.ReadModule (typeof (object).Module.FullyQualifiedName);

But if you inject code that is calling methods in the mscorlib, you don't necessarily have to load the module yourself. For instance:

MethodDefinition method = ...;
ILProcessor il = method.Body.GetILProcessor ();

Instruction call_writeline = il.Create (
    OpCodes.Call, 
    method.Module.Import (typeof (Console).GetMethod ("WriteLine", Type.EmptyTypes)));

Creates an instruction to call Console.WriteLine ();

As for the documentation, please read the importing page on the wiki.

Jb Evain
  • 17,319
  • 2
  • 67
  • 67
  • 2
    Excellect, thanks! I didn't realise you could use .NET reflection objects as well. Cecil documentation is quite hard to come by :/ – thecoop Jul 07 '10 at 15:06
  • 2
    Keep in mind that this code will import the method from the mscorlib for the .NET version of the executing assembly. So if you open a .NET 2.0 assembly and modify it by running the above code under .NET 4.0, the modified assembly will have references to both the 2.0 and 4.0 mscorlib, which is probably not what was intended. – Roman Starkov Jul 28 '13 at 23:02