3

Since CompileAssemblyFromSource add custom functions in a smart way was ignored im going to ask this question differently so people will bother to read it.

cutting at the chase,i am making a language by "translating" the new syntax into c# and compiling it in memory in this fashion.

using (Microsoft.CSharp.CSharpCodeProvider CodeProv =
    new Microsoft.CSharp.CSharpCodeProvider())
    {
        CompilerResults results = CodeProv.CompileAssemblyFromSource(
             new System.CodeDom.Compiler.CompilerParameters()
             {
                 GenerateInMemory = true
             },
             code);

         var type = results.CompiledAssembly.GetType("MainClass");

         var obj = Activator.CreateInstance(type);

         var output = type.GetMethod("Execute").Invoke(obj, new object[] { });

         Console.WriteLine(output);
    }

basically i am executing a "main" function written inside the code variable. and i am using some functions in the code variable i would like to include without adding it as a string at the bottom like this:

        code += @"public void Write(string path, object thevar)
        {
        if (thevar.GetType() == typeof(string))
        {
        System.IO.File.WriteAllText(path,(string)thevar);
        }
        if (thevar.GetType() == typeof(string[]))
        {
        System.IO.File.WriteAllLines(path,(string[])thevar);
        }
        }";

Can i somehow add a class from my Actual main project in VS and let the compiled in memory code access it? without adding it as a string.

Community
  • 1
  • 1
ThatOneLad
  • 51
  • 2
  • Couldn't you add existing assemblies as references? Also, using Roslyn this should be easier. Codedom is not exactly modern. – usr Dec 03 '15 at 17:29
  • 1
    Regarding Stack Overflow usage, your new question is much quicker to comprehend. I advise to delete the old one and drop the first paragraph here. – usr Dec 03 '15 at 17:30
  • If I am understanding you correctly, instead of calling `Invoke` as you do, you can instead pass the result of `GetMethod` (a MethodInfo object) to your class and let _it_ call `Invoke`. Is that what you mean? – 500 - Internal Server Error Dec 03 '15 at 17:39
  • I think he actually meant adding a class file as an accessible reference for the compiled code ,just like you can add strings for the compiler to add-classes. Not sure how i would go about this – downrep_nation Dec 03 '15 at 17:42

1 Answers1

0

You can embed your source code file(s) as resources. With this technique you can edit the file in Visual Studio and access the contents of the files as if it was a string during run-time.

This link shows how to do it: https://stackoverflow.com/a/433182/540832

Community
  • 1
  • 1
Oskar Sjöberg
  • 2,728
  • 27
  • 31