Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top