プログラミングなど

2009年5月22日金曜日

C# + Python embedding C#のクラスをPython側で使用する

C#のクラスをIronPython側で使うのは、非常に簡単だ。
(CPythonだと、結構、面倒だったような...)

---- コード(C#側) ----

using System;

using IronPython;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace python_test001
{
 class Program
 {
  public static void Main(string[] args)
  {
   try
   {
    ScriptEngine engine = Python.CreateEngine();
    ScriptScope scope = engine.CreateScope();

    // C#と変数のやり取りをするPythonのファイルを設定
    ScriptSource source =
     engine.CreateScriptSourceFromFile("test.py");

    TestNumber test = new TestNumber();
    // Python側の変数をTestDataとする
    scope.SetVariable("num", test);

    // 実行
    source.Execute(scope);

    int i = test.Number;

    // 実行後のPython側の変数値を取得

    // 結果を出力 ==> 15
    System.Console.WriteLine(test.Number);
   }
   catch (Exception ex)
   {
    System.Console.WriteLine("Error:"
     + ex.Message.ToString());
   }
  }
 }
}

// Python側に渡すクラス
class TestNumber {
 int number = 0;
 public void Plus(int i) {
  number += i;
 }
 public int GetNumber() {
  return this.number;
 }
 public void SetNumber(int i) {
  this.number = i;
 }
 public int Number {
  get {
   return this.number;
  }
  set {
   this.number = value;
  }
  
 }
}

---- コード(Python側) ----

num.Number = 10
print 'py_number:', num.GetNumber()
#プロパティのgetがprotectedメンバだとかでエラー
#print 'py_number:', num.Number
num.Plus(5)

================================

■参考
貧脚レーサーのサボり日記 - C#でIronPython2.0をホスティングする
Embedding the Dynamic Language Runtime
The IronPython Calculator and the Evaluator

0 件のコメント:

コメントを投稿