IronPython类不是.NET类。它们是IronPython.Runtime.Types.pythotype的实例,后者是Python元类。这是因为Python类是动态的,并且支持在运行时添加和删除方法,这是使用.NET类无法做到的。
要在C中使用Python类,需要使用ObjectOperations类。这个类允许您在语言本身的语义中对python类型和实例进行操作。e、 它在适当的时候使用魔法方法,自动将整数提升为long等。你可以通过查看源代码或使用reflector来了解更多关于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);
如果您将Visual Studio 2010或更高版本与NuGet支持一起使用,只需执行此操作即可下载并引用相应的库。Install-Package IronPython