Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top