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.
views:
31answers:
1
+2
A:
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
2010-07-07 14:50:42
Excellect, thanks! I didn't realise you could use .NET reflection objects as well. Cecil documentation is quite hard to come by :/
thecoop
2010-07-07 15:06:35