プログラミングなど

2009年5月17日日曜日

C# + Python embedding 簡単な計算

CC#からIronPythonに計算させる簡単な例。

■.NET Framework2.0 sp1で実行
 sp1でないと動かない点に注意
■IronPython 2.0
 以下からIronPython-2.0.1-Bin.zipをダウンロード
 http://www.codeplex.com/IronPython → Downloads

 以下を参照設定で追加
  IronPython.dll
  IronPython.Modules.dll
  Microsoft.Scripting.Core.dll
  Microsoft.Scripting.dll
  Microsoft.Scripting.ExtensionAttribute.dll

---- コード ----

using System;

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

...

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

        // 1 + 2 を Python に計算させる
        ScriptSource source =
          engine.CreateScriptSourceFromString(
            "1 + 2", SourceCodeKind.Expression);
        object res = source.Execute();
        // 結果を出力 ==> 3
        System.Console.WriteLine(res);
      }
      catch (Exception ex)
      {
        System.Console.WriteLine("Error:" +
          ex.Message.ToString());
      }
    }

0 件のコメント:

コメントを投稿