现在的位置: 首页 > 综合 > 正文

IronPython脚本程序与宿主语言的交互

2013年08月24日 ⁄ 综合 ⁄ 共 826字 ⁄ 字号 评论关闭

随着web2.0和敏捷开发方法论的兴起,动态语言的灵活高效的特性成为了它被更多项目选择和使用的理由。一些大型网站已开始使用动态语言来实现。微软更是不甘落后,建立了dlr(动态语言运行时)来吸引动态语言爱好者在其上实现动态语言。ironpython就是其主要成员之一。

// 定义一个业务对象
class businessobject 
{
   private string oneproperty;

   public string oneproperty
   {
      get { return oneproperty; }
      set { oneproperty = value; }
   }

   public void onemethod(string val)
   {
      // do something...
   }
}

// 取得当前的engine
scriptengine engine = pythonengine.currentengine;

// 取得scope
scriptscope scope = engine.createscope();

businessobject bo = new businessobject();
bo.oneproperty = 10;

// 设置变量,这是交互的关键!
scope.setvariable("bo", bo);

// 这是要招待的脚本, bo即从宿主传递过来的对象
string code = "bo.oneproperty = '中文'/n";
code += "bo.onemethod('参数')";

// 创建scriptsource
scriptsource source = engine.createscriptsourcefromstring(code, sourcecodekind.statements);

// 执行脚本
source.execute(scope);

可以预见,通过这个交互的方式,可以将一些逻辑代码从宿主环境中剥离出来,
改由ironpython进行处理,这样可以增强系统的灵活性。

抱歉!评论已关闭.