Is there a good wrapper around ILGenerator?

I have been using System.Reflection.Emit for a while and find it (who is not?) As painful as error prone.

Do you know if there is a good shell around the IL generator that I can rely on to emit IL in a safer and easier way than with direct SRE playback?

Edit:

I know that manipulating expression trees is ultimately simpler and safer than directly emitting IL, but they also have some limitations right now. I cannot create blocks of code, use loops, declare and work with multiple locals, etc. We need to wait until .NET 4 comes out :)

In addition, I am dealing with a code base that already relies on SRE.

Obviously, ILGenerator does everything I need. But I will be grateful for the help in managing it. When I mean the ILGenerator shell, which remains at a fairly low level, I think of something that can provide methods such as:

// 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) 

These are really 3 naive examples, but this may be enough to demonstrate what I expect. We can see this as a set of extension methods, but it would be nice to have support for conditional statements and loops, for example, in RunSharp . In fact, RunSharp is pretty close to what I want, but it abstracts too far ILGenerator and does not reveal all its functionality.

I can’t remember where, but I have already seen such an assistant in an open source project.

+7
c # cil
source share
3 answers

If you are using .NET 3.5, you may find using expression trees more sensible. It completely depends on what you are doing - and it can be quite painful, but it is certainly another option that you need to know about.

+6
source share

[updated]: I was thinking about the name; -p RunSharp . I cannot vouch for this, but it may be what you need.

Nevertheless; what do you need to create? CodeDom is one option. To create methods, you may find that you can do a lot more than you expect with the Expression class in .NET 3.5 (after compilation it is the dialed delegate through Expression.Lambda / Compile.

+4
source share

Try using Mono.Cecil

Cecil is a library written by Jb Evain to generate and test programs and libraries in ECMA CIL format. It has full generic support and support for some debug symbol format.

+2
source share

All Articles