如何在.NET中实现脚本引擎 (CodeDom篇)

        .NET 本身提供了强大的脚本引擎,可以直接使用.NET CLR的任何编程语言作为脚本语言,如VB.NET、C#、JScript, J#等等。使用脚本引擎,我们可以动态生成任意表达式、或动态导入任意脚本文件,并在任意时候执行。
        经实践发现,我们可以使用至少两种不同的方式在.NET中使用脚本引擎:VsaEngine和CodeDom。
        其实,CodeDom不能算是真正的脚本引擎,它实际上是编译器。但是我们完全可以利用CodeDom来模拟脚本引擎。
        使用Emit方法也能达到动态生成可执行代码的目的,而且Emit生成的代码不需要编译,因此速度更快。但是Emit插入的实际上是汇编代码,不能算是脚本语言。
        本文介绍如何以CodeDom方式来动态生成可执行代码。

如何在.NET中实现脚本引擎 (CodeDom篇)    沐枫网志

    1.     构造一个编译器

  • 设置编译参数
    编译参数需要在CompilerParameters设置: 

CompilerOptions用于设置编译器命令行参数
IncludeDebugInformation用于指示是否在内存在生成Assembly
GenerateInMemory用于指示是否在内存在生成Assembly
GenerateExecutable用于指示生成的Assembly类型是exe还是dll
OutputAssembly用于指示生成的程序文件名(仅在GenerateInMemory为false的情况)
ReferencedAssemblies用于添加引用Assembly

例如:

None.gif theParameters.ReferencedAssemblies.Add( " System.dll ");
None.gif
  • 创建指定语言的编译器
    编译需要由指定语言的CodeDomProvider生成。

这里列举一些.NET的CodeDomProvider:        

vb.net Microsoft.VisualBasic.VBCodeProvider
C#Microsoft.CSharp.CSharpCodeProvider
jscriptMicrosoft.JScript.JScriptCodeProvider
J#Microsoft.VJSharp.VJSharpCodeProvider

以C#为例,要创建C#编译器,代码如下: 

None.gif CodeDomProvider theProvider =  (ICodeCompiler)  new Microsoft.CSharp.CSharpCodeProvider();
None.gif

下面是完整的创建编译器的例子:

ExpandedBlockStart.gif ContractedBlock.gif          /**//// <summary>
InBlock.gif        /// 创建相应脚本语言的编译器
ExpandedBlockEnd.gif        /// </summary>
None.gif          private   void  createCompiler( string  strLanguage,  bool  debugMode,  string strAssemblyFileName)
ExpandedBlockStart.gifContractedBlock.gif         dot.gif{
InBlock.gif            
this.theParameters = new CompilerParameters();
InBlock.gif            this.theParameters.OutputAssembly = System.IO.Path.Combine(System.IO.Path.GetTempPath(), strAssemblyFileName + ".dll");
InBlock.gif            this.theParameters.GenerateExecutable = false;
InBlock.gif            this.theParameters.GenerateInMemory = true;
InBlock.gif            if(debugMode)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                
this.theParameters.IncludeDebugInformation = true;
InBlock.gif                this.theParameters.CompilerOptions += "/define:TRACE=1 /define:DEBUG=1 ";
ExpandedSubBlockEnd.gif            }
InBlock.gif            else
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                
this.theParameters.IncludeDebugInformation = false;
InBlock.gif                this.theParameters.CompilerOptions += "/define:TRACE=1 ";
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            AddReference("System.dll");
InBlock.gif            AddReference("System.Data.dll");
InBlock.gif            AddReference("System.Xml.dll");
InBlock.gif
InBlock.gif            strLanguage = strLanguage.ToLower();
InBlock.gif 
InBlock.gif            if("visualbasic" == strLanguage || "vb" == strLanguage)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                theProvider 
= new Microsoft.VisualBasic.VBCodeProvider();
InBlock.gif                if(debugMode)
InBlock.gif                    theParameters.CompilerOptions += "/debug:full /optimize- /optionexplicit+ /optionstrict+ /optioncompare:text /imports:Microsoft.VisualBasic,System,System.Collections,System.Diagnostics ";
InBlock.gif                else
InBlock.gif                    theParameters.CompilerOptions += "/optimize /optionexplicit+ /optionstrict+ /optioncompare:text /imports:Microsoft.VisualBasic,System,System.Collections,System.Diagnostics ";
InBlock.gif                AddReference("Microsoft.VisualBasic.dll");
ExpandedSubBlockEnd.gif            }
InBlock.gif            else if("jscript" == strLanguage || "js" == strLanguage)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                theProvider 
= new Microsoft.JScript.JScriptCodeProvider();
InBlock.gif                AddReference("Microsoft.JScript.dll");
ExpandedSubBlockEnd.gif            }
InBlock.gif            else if("csharp" == strLanguage || "cs" == strLanguage || "c#" == strLanguage)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                theProvider 
= new Microsoft.CSharp.CSharpCodeProvider();
InBlock.gif                if(!debugMode)
InBlock.gif                    theParameters.CompilerOptions += "/optimize ";
ExpandedSubBlockEnd.gif            }
InBlock.gif//            else if("jsharp" == strLanguage || "vj" == strLanguage || "j#" == strLanguage)
InBlock.gif//            {
InBlock.gif//                theProvider = new Microsoft.VJSharp.VJSharpCodeProvider();
InBlock.gif//                if(!debugMode)
InBlock.gif//                    theParameters.CompilerOptions += "/optimize ";
InBlock.gif//            }
InBlock.gif            else
InBlock.gif                throw new System.Exception("指定的脚本语言不被支持。"); 
ExpandedBlockEnd.gif        }
None.gif
ExpandedBlockStart.gifContractedBlock.gif         /**//// <summary>
InBlock.gif        /// 添加引用对象。
InBlock.gif        /// </summary>
ExpandedBlockEnd.gif        /// <param name="__strAssemblyName">引用的文件名</param>
None.gif          public   void  AddReference( string __strAssemblyName)
ExpandedBlockStart.gifContractedBlock.gif         dot.gif{
InBlock.gif            theParameters.ReferencedAssemblies.Add(__strAssemblyName);
ExpandedBlockEnd.gif        }

None.gif


2.     编译源代码 

        编译源代码相当简单,只需一条语句就搞定了:

None.gif CompilerResults compilerResults  = compiler.CompileAssemblyFromSource( this .theParameters,  this .SourceText); 

执行后,可以从compilerResults取得以下内容: 

NativeCompilerReturnValue 编译结果,用于检查是否成功
Errors 编译时产生的错误和警告信息
CompiledAssembly 如果编译成功,则返回编译生成的Assembly

  
示例函数: 

ExpandedBlockStart.gif ContractedBlock.gif          /**//// <summary>
InBlock.gif        /// 编译脚本。编译前将清空以前的编译信息。
InBlock.gif        /// CompilerInfo将包含编译时产生的错误信息。
InBlock.gif        /// </summary>
ExpandedBlockEnd.gif        /// <returns>成功时返回True。不成功为False。</returns>
None.gif          public   bool Compile()
ExpandedBlockStart.gifContractedBlock.gif         dot.gif{
InBlock.gif            
this.theCompilerInfo = "";
InBlock.gif            this.isCompiled = false;
InBlock.gif            this.theCompiledAssembly = null;
InBlock.gif            // 下面一行代码仅用于.NET 2.0
InBlock.gif            this.theCompilerResults = this.theProvider.CompileAssemblyFromSource(this.theParameters, this.SourceText);
InBlock.gif            // 下面一行代码用于.NET1.1(与.NET2.0的区别是,.NET2.0不需要调用CreateCompiler)
InBlock.gif            // this.theCompilerResults = this.theProvider.CreateCompiler().CompileAssemblyFromSource(this.theParameters, this.SourceText);
InBlock.gif
InBlock.gif            if(this.theCompilerResults.NativeCompilerReturnValue == 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                
this.isCompiled = true;
InBlock.gif                this.theCompiledAssembly = this.theCompilerResults.CompiledAssembly;
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            System.Text.StringBuilder compilerInfo = new System.Text.StringBuilder();
InBlock.gif
InBlock.gif            foreach(CompilerError err in this.theCompilerResults.Errors)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                compilerInfo.Append(err.ToString());
InBlock.gif                compilerInfo.Append(
"\r\n");
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            theCompilerInfo 
= compilerInfo.ToString();
InBlock.gif
InBlock.gif            return isCompiled;
ExpandedBlockEnd.gif        }
None.gif



    3.     执行代码

使用Reflection机制就可以很方便的执行Assembly中的代码。
我们假设编译时使用的脚本代码 this.SourceText 内容如下:

None.gif namespace test 
ExpandedBlockStart.gifContractedBlock.gif dot.gif
InBlock.gif    
public class script 
ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif
InBlock.gif        public 
static void Main() 
ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif
InBlock.gif            MessageBox.Show(
"Hello"); 
ExpandedSubBlockEnd.gif        } 
ExpandedSubBlockEnd.gif    }
 
ExpandedBlockEnd.gif}
 
None.gif

则相应的执行代码为:

None.gif scriptEngine.Invoke( " test.script " " Main " null);
None.gif

注意:Invoke调用的函数必须是静态的。

Invoke函数内容:

ExpandedBlockStart.gif ContractedBlock.gif          /**//// <summary>
InBlock.gif        /// 执行指定的脚本函数(Method)。
InBlock.gif        /// 如果指定的类或模块名,以及函数(Method)、或参数不正确,将会产生VsaException/VshException例外。
InBlock.gif        /// </summary>
InBlock.gif        /// <param name="__strModule">类或模块名</param>
InBlock.gif        /// <param name="__strMethod">要执行的函数(Method)名字</param>
InBlock.gif        /// <param name="__Arguments">参数(数组)</param>
ExpandedBlockEnd.gif        /// <returns>返回执行的结果</returns>
None.gif          public   object  Invoke( string  __strModule,  string  __strMethod,  object[] __Arguments)
ExpandedBlockStart.gifContractedBlock.gif         dot.gif{
InBlock.gif            
if(!this.IsCompiled || this.theCompiledAssembly == null)
InBlock.gif                throw new System.Exception("脚本还没有成功编译");
InBlock.gif
InBlock.gif            Type __ModuleType = this.theCompiledAssembly.GetType(__strModule);
InBlock.gif            if(null == __ModuleType)
InBlock.gif                throw new System.Exception(string.Format("指定的类或模块 ({0}) 未定义。", __strModule));
InBlock.gif
InBlock.gif            MethodInfo __MethodInfo = __ModuleType.GetMethod(__strMethod);
InBlock.gif            if(null == __MethodInfo)
InBlock.gif                throw new System.Exception(string.Format("指定的方法 ({0}::{1}) 未定义。", __strModule, __strMethod));
InBlock.gif
InBlock.gif            try
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                
return __MethodInfo.Invoke(null, __Arguments);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch( TargetParameterCountException )
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                
throw new System.Exception(string.Format("指定的方法 ({0}:{1}) 参数错误。", __strModule, __strMethod));
ExpandedSubBlockEnd.gif            }
InBlock.gif            
catch(System.Exception e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
InBlock.gif                System.Diagnostics.Trace.WriteLine(
string.Format("执行({0}:{1})错误: {2}", __strModule, __strMethod, e.ToString()));
InBlock.gif                return null;
ExpandedSubBlockEnd.gif            }
ExpandedBlockEnd.gif        }

None.gif


总结:

        CodeDom可以很方便的随时编译源代码,并动态执行。虽然作为脚本引擎,它没有VsaEngine正规和方便,但作为一般应用,也够用了。并且结合Reflection机制,它的功能比VsaEngine更强大:它可以编译任何提供CompilerProvider的CLR语言(目前.NET自带的语言中都有)。 
        当然,它也有一些缺点:它生成的Assembly不能动态卸载。这在一般情况下不成问题,因为一个源代码只需编译一次,并载入执行,并不需要动态卸载。 
        假如你需要做脚本编辑器时,就要考虑这个问题,因为有可能一个脚本会因为修修改改而不停的重新编译,从而造成不停的产生新的Assembly,最后将导致内存被大量占用。要解决这个问题,需要将编译器加载到独立的AppDomain中,通过卸载AppDomain达到卸载所需的Assembly的目的。

附件为完整的源代码,以供测试:
http://files.cnblogs.com/ly4cn/netScript.rar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值