如何运行内存创建的DLL并使用C#和反射从中检索值

时间:2011-03-05 08:32:41

标签: c# reflection scripting

我想创建一个简单的脚本引擎,以便在程序的某些不可预知的情况下使用它。

我可以在内存EXE文件中运行,但我不知道如何运行内存DLL。 这是我的引擎(从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.ReferencedAssemblies.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);
            }
        }

这是我想在运行时从中检索值的简单DLL:

//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;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

类似的东西:

    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);
    }

特别是:

  • 这不是一个切入点;这只是一种随意的方法
  • 因为它是静态方法,所以您不需要创建实例