I'm using System.Reflection.Emit for a while now, and find it (who don't?) as painful as bug prone.
Do you know if there is a good wrapper around the IL Generator, something that I can rely on to emit IL in a more safe and easier manner than with playing directly with SRE?
Edit:
I know that manipulating expression trees is definitively easier and safer than emitting IL directly, but they also have some constraints right now. I can't create code blocs, use loops, declare and work with several locals, etc. We need to wait until .NET 4 comes out :)
Moreover, I'm dealing with a code base which already relies on SRE.
Obviously, ILGenerator do everything I need. But I would appreciate more assistance when manipulating it. When I'm referring to a ILGenerator wrapper, which remains at a pretty low level, I think about something which could provide methods like:
// Performs a virtual or direct call on the method, depending if it is a
// virtual or a static one.
Call(MethodInfo methodInfo)
// Pushes the default value of the type on the stack, then emit
// the Ret opcode.
ReturnDefault(Type type)
// Test the object type to emit the corresponding push
// opcode (Ldstr, Ldc_I*, Ldc_R*, etc.)
LoadConstant(object o)
It's really 3 naive examples, but it could be enough to demonstrate what I expect. We can see that as a set of extension methods, but it could be nice to have support for conditional statements and loops like in RunSharp. In fact, RunSharp is pretty close that what I want, but it abstracts the ILGenerator too much and doesn't expose all its functionality.
I can't remember where, but I already saw such an helper in an open source project.
If you're using .NET 3.5, you may find using Expression Trees to be more reasonable. It entirely depends on what you're doing - and it can still be quite painful - but it's certainly another option to be aware of.
[updated]: I thought of the name ;-p RunSharp. I can't vouch for it, but it might be what you need.
However; what do you need to generate? CodeDom is one option. For creating methods, you might find that you can do a lot more than you expect with the Expression class in .NET 3.5 (after compiling it to a typed delegate via Expression.Lambda/Compile.
Try using Mono.Cecil
Cecil is a library written by Jb Evain to generate and inspect programs and libraries in the ECMA CIL format. It has full support for generics, and support some debugging symbol format.
来源:https://stackoverflow.com/questions/197005/is-there-a-good-wrapper-around-ilgenerator