Is there a way to dynamically insert bytecode directly into my C# executable? I'm looking for functionality similar to the asm keyword in C++. Obviously I know I can't insert x86 assembly instructions. I'd only be able insert IL Bytecode.
Yes, you can use DynamicMethod
s which basically do exactly this (you get a Delegate to invoke the code that you've generated with the dynamic method).
In fact, several framework parts seem to use them, including the compiled XSL transformations, the compiled Regular Expressions etc. They work very well and they are pretty performant (after the initial overhead for creating/compiling them).
you can use Reflection.Emit directy - you must create an Assembly/Module/Class/Method and insert the IL on the method body.
--
With .Net 2.0 you can use DynamicMethod that can be compiled in a delegate, so you don't need to create the Assembly/Module/Class dynamically.
--
With .Net 3.0 you can use ExpressionTrees to dynamically generate the code and attach to a delegate.
--
Hope this helps.
Ricardo Lacerda Castelo Branco