C#|IronPython|C#でIronPython2.0をホスティングする

http://www.voidspace.org.uk/ironpython/ip_in_ip.shtml (英語)

英語は読めないからソースだけ読んで参考にしました。

【参照設定】

IronPython2.0のディレクトリより

IronPython.dll

Microsoft.Scripting.Core.dll

Microsoft.Scripting.dll

【Form1.cs】

using System;

using System.Windows.Forms;

using IronPython.Hosting;

using Microsoft.Scripting.Hosting;

public partial class Form1 :Form {

  public Form1() {

    InitializeComponent();

  }

  private void button1_Click(object sender, EventArgs e) {

    ScriptEngine engine = Python.CreateEngine();

    ScriptSource source =

        engine.CreateScriptSourceFromFile(“./test.py”);

    ScriptScope scope = engine.CreateScope();

    //IronPythonにformという変数名でthisを渡す。

    scope.SetVariable(“form”, this);

    //ここで実行

    source.Execute(scope);

    //IronPythonのtestVarという変数のオブジェクトを取得する。

    object value = scope.GetVariable(“testVar”);

    this.button1.Text = (string)value;

  }

}

【test.py】

form.Text = “Hello,World!”

testVar = “test”

こんな感じで、IronPython側にオブジェクトを渡してIronPython側で操作したり、IronPython側のオブジェクトをC#側で取得することが出来ました。

IronPythonとのオブジェクトのやり取りはScriptScopeオブジェクトを通して行うんですね。

これだけでもかなり面白いです。IronPython1.0からはかなり勝手が変わったようです。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください