开发者

how to run a in memory created DLL and retrieve value from it using C# and reflection

I want to create a simple script engine to use it in some of unpredicted situation in my program.

I can run in memory EXE file but I don't have any idea of how to run a in memory DLL. here is my engine(got it from vsj.co.uk) :

 CSharpCodeProvider prov = new CSharpCodeProvider();
            ICodeCompiler compiler = prov.CreateCompiler();
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;

            cp.ReferencedAssemblies.Add("system.dll");
            cp.ReferencedAssemblies.Add("system.xml.dll");
            cp.Refere开发者_运维百科ncedAssemblies.Add("system.data.dll");
            cp.ReferencedAssemblies.Add("system.windows.forms.dll");

            CompilerResults cr;
            cr = compiler.CompileAssemblyFromSource(cp, File.ReadAllText(@"c:\test\sc2.csx"));

            Assembly a = cr.CompiledAssembly;
            try {
                object o = a.CreateInstance(
                    "CSharpScript");
                MethodInfo mi = a.EntryPoint;
                mi.Invoke(o, null);
            }
            catch(Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }

and here is my simple DLL that I want to retrieve value from it during run-time:

//sc2.csx
using System;
using System.Collections.Generic;
using System.Text;


namespace dynamic_scripting
{
    public class DynScripting
    {
        public static int executeScript(string script)
        {
            return 1;
        }
    }
}


Something like:

    Assembly a = cr.CompiledAssembly;
    try {
        Type type = a.GetType("dynamic_scripting.DynScripting");
        int result = (int) type.GetMethod("executeScript").Invoke(
            null, new object[] {"CSharpScript" });
    }
    catch(Exception ex) {
        MessageBox.Show(ex.Message);
    }

in particular:

  • this isn't really an entry-point; it is just an arbitrary method
  • since it is a static method, you don't need to create an instance
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜