Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile and run dynamic code, without generating EXE?

Tags:

I was wondering if it was possible to compile, and run stored code, without generating an exe or any type of other files, basically run the file from memory.

Basically, the Main application, will have some stored code (code that will potentially be changed), and it will need to compile the code, and execute it. without creating any files.

creating the files, running the program, and then deleting the files is not an option. the compiled code will need to be ran from memory.

code examples, or pointers, or pretty much anything is welcome :)

like image 750
caesay Avatar asked Jul 06 '10 17:07

caesay


People also ask

Is it possible to dynamically compile and execute C# code fragments?

Yeah, the nice thing with CodeDOM is that it can generate the assembly for you in memory (as well as providing error messages and other info in an easily readable format). @Noldorin, The C# CodeDOM implementation doesn't actually generate an assembly in memory.

What is CodeDOM compiler?

CodeDom. Compiler namespace provides interfaces for generating source code from CodeDOM object graphs and for managing compilation with supported compilers. A code provider can produce source code in a particular programming language according to a CodeDOM graph.

Does C# compile to exe?

After a developer writes the C# code, he or she compiles their code. This results in Common Intermediate Language stored within Portable Executable (PE for 32-bit, PE+ for 64-bit) files such as “.exe” and “. dll” files for Windows. These files are distributed to users.

How compile and run in C sharp?

To compile and execute a program in C#, you just need to click the Run button or press F5 key to execute the project in Microsoft Visual Studio IDE. Open a text editor and add the above-mentioned code. Open the command prompt tool and go to the directory where you saved the file. Type csc helloworld.


1 Answers

using (Microsoft.CSharp.CSharpCodeProvider foo =             new Microsoft.CSharp.CSharpCodeProvider()) {     var res = foo.CompileAssemblyFromSource(         new System.CodeDom.Compiler.CompilerParameters()          {               GenerateInMemory = true          },          "public class FooClass { public string Execute() { return \"output!\";}}"     );      var type = res.CompiledAssembly.GetType("FooClass");      var obj = Activator.CreateInstance(type);      var output = type.GetMethod("Execute").Invoke(obj, new object[] { }); } 

This compiles a simple class from the source code string included, then instantiates the class and reflectively invokes a function on it.

like image 153
Adam Robinson Avatar answered Sep 28 '22 03:09

Adam Robinson