IronPython では、C# で定義したクラスを継承したり、インタフェースを実装することができます。
C# 側
namespace PythonSampleLib { public abstract class Greeting { public abstract string Greet(string name); } }
using System; using System.IO; using IronPython.Hosting; using Microsoft.Scripting.Hosting; using PythonSampleLib; namespace PythonSample { class Program { static void Main(string[] args) { string path = Path.Combine( Path.GetDirectoryName(typeof(Program).Assembly.Location), "Sample.py"); ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); ScriptSource source = engine.CreateScriptSourceFromFile(path); // Python スクリプトを実行 source.Execute(scope); // Python スクリプト内で定義したクラスのインスタンスを取得 Greeting greeting = scope.GetVariable<Greeting>("greeting"); Console.WriteLine(greeting.Greet("Hideki")); Console.ReadLine(); } } }
IronPython 側
import clr # dll しか参照できない。 # exe だと失敗する。 clr.AddReference("PythonSampleLib") from PythonSampleLib import * # C# で定義した Greeting を継承 class HelloGreeting(Greeting): def Greet(self, name): return "Hello, " + name + "!" # インスタンスを生成して変数に格納しておく。 # C# 側で取得するため。 greeting = HelloGreeting()
実行結果
IronPython では exe を参照できません。実行時に例外が発生します。なので、Greeting クラスはクラスライブラリとして用意しました。
C# から IronPython 側で定義したクラスを利用するために、IronPython 側でインスタンスを生成して変数に格納しています。本当は C# 側でインスタンスを生成したかったのですが、方法が見つからなかったもので…。