Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mono-Cecil: How can I get a ModuleDefinition for mscorlib?

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.

like image 852
thecoop Avatar asked Jul 07 '10 14:07

thecoop


1 Answers

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.

like image 180
Jb Evain Avatar answered Sep 24 '22 23:09

Jb Evain