c#解释器执行的最佳方式
本文关键字:最佳 方式 执行 解释器 | 更新日期: 2023-09-27 18:10:12
我正在编写一种脚本语言,我已经完成了词法分析器和解析器,我想在内存中动态执行。
假设我有一个像
这样的东西function Hello(World)
{
Print(world);
}
var world = "World";
var boolean = true;
if(boolean == true)
{
Print("True is True");
}
else
{
Print("False is True");
}
Hello(world);
执行这段代码的最好方法是什么?
1) OpCode Il生成(我无法获得if语句工作或任何其他打印函数)2) RunSharp,我不能做这些函数,因为我不知道怎么做。
如果有人能给我指出正确的方向!
一点点代码会有帮助链接到资源(不像IronPython)也会很好
你的脚本语言像JavaScript,如果它在内存中动态编译。
的例子:
//csc sample.cs -r:Microsoft.JScript.dll
using System;
using System.CodeDom.Compiler;
using Microsoft.JScript;
class Sample {
static public void Main(){
string[] source = new string[] {
@"import System;
class JsProgram {
function Print(mes){
Console.WriteLine(mes);
}
function Hello(world){
Print(world);
}
function proc(){
var world = ""World"";
var bool = true;
if(bool == true){
Print(""True is True"");
}
else{
Print(""False is True"");
}
Hello(world);
}
}"
};
var compiler = new JScriptCodeProvider();
var opt = new CompilerParameters();
opt.ReferencedAssemblies.Add("System.dll");
opt.GenerateExecutable = false;
opt.GenerateInMemory = true;
var result = compiler.CompileAssemblyFromSource(opt, source);
if(result.Errors.Count > 0){
Console.WriteLine("Compile Error");
return;
}
var js = result.CompiledAssembly;
dynamic jsProg = js.CreateInstance("JsProgram");
jsProg.proc();
/*
True is True
World
*/
}
}
生成c#源代码并编译:-)http://support.microsoft.com/kb/304655
如果我理解对了,你想在运行时编译和运行代码吗?然后你可以尝试http://www.csscript.net/index.html,它的一个例子在同一页链接。