views:

118

answers:

2

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.

+5  A: 

Yes, you can use DynamicMethods 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).

Lucero
Exactly what I was looking for! Thanks dude!
icemanind
You're welcome. Some interesting information can be found tagged here on SO: http://stackoverflow.com/questions/tagged/dynamicmethod (and one sample by me here: http://stackoverflow.com/questions/1516119 ) - have fun! ;)
Lucero
+1  A: 

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

Ricardo Lacerda Castelo Branco