Modifying class at runtime

L

Lord Zoltar

Is it possible with the classes in Reflection.Emit to modify a method
of an existing class?
I would like to print some diagnostic messages every time certain
methods are called. I don't want to start adding code to every part of
my program that calls these methods, and the code came as a DLL so I
can't modify the source.

Here's something close to what I've tried:

Assembly currentAssembly = Assembly.GetExecutingAssembly();
Type[] types = currentAssembly.GetTypes();
....//other unrelated code removed...
AppDomain appDomain = AppDomain.CurrentDomain;
AssemblyBuilder assbuild =
appDomain.DefineDynamicAssembly(currentAssembly.GetName(),
AssemblyBuilderAccess.Run);
//types[j] is the index in types of the type I need to modify.
ModuleBuilder myModuleBuilder =
assbuild.DefineDynamicModule(types[j].Module.Name);

TypeBuilder myTypeBuilder = myModuleBuilder.DefineType(t.Name,
TypeAttributes.Public);

MethodBuilder myMethod = myTypeBuilder.DefineMethod(mi.Name,
MethodAttributes.Public, CallingConventions.Standard, null,
myMethodArgs);

ILGenerator methodIL = myMethod.GetILGenerator();
methodIL.EmitWriteLine("Trace method: " + mi.Name);
methodIL.Emit(OpCodes.Nop,
mi.GetMethodBody().GetILAsByteArray().ToString());
types[j] = myTypeBuilder.CreateType();

I had hoped that the line
types[j]=myTypeBuilder.CreateType();
but when I try to use objects of this type, the logging statement does
not appear. Is what I'm trying to do even possible?
 
J

Jon Skeet [C# MVP]

Lord Zoltar said:
Is it possible with the classes in Reflection.Emit to modify a method
of an existing class?
I would like to print some diagnostic messages every time certain
methods are called. I don't want to start adding code to every part of
my program that calls these methods, and the code came as a DLL so I
can't modify the source.

If you can't modify the source, you may *legally* not be allowed to do
anything. However, PostSharp (http://www.postsharp.org) may be able to
help you.
 
L

Lord Zoltar

If you can't modify the source, you may *legally* not be allowed to do
anything. However, PostSharp (http://www.postsharp.org) may be able to
help you.

Heh it's not so much a legal matter as I compiled an old project to
DLL and didn't really want to add debug statements all over it and
rebuild it... I thought it would be much cleaner to just add the debug
logging in the new project, and I was also kinda curious to play with
the Emit namespace...
That PostSharp system looks very interesting, I'll definitely have to
give it a look. Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top