views:

232

answers:

3

I've built some Types dynamically using System.CodeDom.CodeCompileUnit, want to compile those into IL code in memory, and inject that IL code into an assembly loaded in memory - there is no need to save any of this to disk. Maybe my stated plan is wrong. Open to other suggestions about how to get that CodeCompileUnit instance to the said destination.

+4  A: 

You can inject code into an existing (already loaded) assembly using ICorDebug interfaces. Edit and Continue does it.

Compute your delta bytes and call ICorDebugModule2::ApplyChanges. See the MDbg sample code for more details.

Once upon a time we used ICorDebugModule::GetEditAndContinueSnapshot and kin, but these are now deprecated.

Update If you don't care about injecting code into an already-loaded assembly, just using Reflection.Emit to create a new assembly is more efficient and a lot easier.

Ray Burns
This solution directly answers the question. Thanks.
John K
+1  A: 

You can also use System.Reflection.Emit namespace and create a dynamic, in-memory assembly.

Alternative is to use CodeDom to generate & compile code, then call into it.

XMLSerialization() does the latter.

feroze
A: 

You can use Mono.Cecil to manipulate IL. It's a powerfull tool, though it somehow lacks documentation.

Bolek Tekielski