Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(C#) Compiling class at runtime and calling methods from original code


I'm trying to compile code at runtime in C#, then from the compiled code call a function or initialize a class which is defined in the original code.
The code I currently have:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

namespace CTFGame
{
    class Program
    {
        static void Main(string[] args)
        {
            string code = @"

using System;

namespace CTFGame
{
    public class MyPlayer
    {
        public static void Main ()
        {
            Console.WriteLine(""Hello world"");
        }
        /*public void DoTurn ()
        {
            Program.SayHello();
        }*/
    }
}

";
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;

            CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
            if (results.Errors.HasErrors)
            {
                string errors = "";
                foreach (CompilerError error in results.Errors)
                {
                    errors += string.Format("Error #{0}: {1}\n", error.ErrorNumber, error.ErrorText);
                }
                Console.Write(errors);
            }
            else
            {
                Assembly assembly = results.CompiledAssembly;
                Type program = assembly.GetType("CTFGame.MyPlayer");
                MethodInfo main = program.GetMethod("Main");
                main.Invoke(null, null);
            }
        }

        public static void SayHello()
        {
            Console.WriteLine("I'm awesome ><");
        }
    }
}

Now, Running the runtime loaded method 'Main' is a success, and the message "Hello world" is printed. The problem starts here: in the original code I have a method called "SayHello". I want to call this method from my runtime loaded code.
If I uncomment the "DoTurn" method, a compiler error will show in runtime:

Error #CS0103: The name 'Program' does not exist in the current context



My question is - is this possible, and how?

Putting the runtime loaded code in the same namespace doesn't help (and that makes sense), so what is the correct way to do that?

Thanks.

like image 296
Yotam Salmon Avatar asked Apr 12 '16 19:04

Yotam Salmon


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


1 Answers

Adding a reference to the current assembly solved the problem:

CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;                
//The next line is the addition to the original code
parameters.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);

More about: Compiling c# at runtime with user defined functions

like image 121
Yotam Salmon Avatar answered Oct 15 '22 01:10

Yotam Salmon