IronPython クラスは.NET クラスではありません。これらは、Python メタクラスである IronPython.Runtime.Types.PythonType のインスタンスです。これは、Python クラスが動的であり、実行時のメソッドの追加と削除をサポートしているためです。これは、.NET クラスでは実行できないことです。
C# で Python クラスを使用するには、ObjectOperations クラスを使用する必要があります。このクラスを使用すると、言語自体のセマンティクスで Python の型とインスタンスを操作できます。たとえば、必要に応じて魔法のメソッドを使用したり、整数を long に自動昇格させたりします。ソースを参照するか、リフレクターを使用すると、ObjectOperations の詳細を確認できます。
ここに例があります。Calculator.py には単純なクラスが含まれています。
class Calculator(object):
def add(self, a, b):
return a + b
次のように、.NET 4.0 より前の C# コードから使用できます。
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
ScriptScope scope = engine.CreateScope();
ObjectOperations op = engine.Operations;
source.Execute(scope); // class object created
object klaz = scope.GetVariable("Calculator"); // get the class object
object instance = op.Call(klaz); // create the instance
object method = op.GetMember(instance, "add"); // get a method
int result = (int)op.Call(method, 4, 5); // call method and get result (9)
アセンブリ IronPython.dll、Microsoft.Scripting、および Microsoft.Scripting.Core を参照する必要があります。
C# 4 では、新しい動的な型を使用してこれがはるかに簡単になりました。
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
dynamic Calculator = scope.GetVariable("Calculator");
dynamic calc = Calculator();
int result = calc.add(4, 5);
NuGet をサポートする Visual Studio 2010 以降を使用している場合は、これを実行するだけで、適切なライブラリをダウンロードして参照できます。
Install-Package IronPython