在没有样板的情况下从 IronPython 实例化 .Net class

Instantiate a .Net class from IronPython without boilerplate

要在 IronPython 中使用来自 .Net 主机应用程序的 class,您可以这样做:

import clr
clr.AddReference('MyApplication')
from MyApplication import MyClass

x = MyClass()

但是如果没有前 3 行或者在主机应用程序运行脚本之前以某种方式执行它们,我怎么能做到呢?

Microsoft.Scripting.Hosting(它是 IronPython 中使用的动态语言运行时的一部分)中,您有一个 ScriptScope 的概念,您可以在其上执行语句或源脚本。

这允许您在执行实际脚本之前在作用域上执行样板文件。以下示例显示了基本思想:

var engine = Python.CreateEngine();
var scope = engine.CreateScope();

var boilerplateSourceText = @"import clr
clr.AddReference('MyApplication')
from MyApplication import MyClass
";

var boilerplateSource = engine.CreateScriptSourceFromString(boilerplateSourceText, SourceCodeKind.Statements);
boilerplateSource.Execute(scope);

var scriptSource = engine.CreateScriptSourceFromString("x = MyClass()", SourceCodeKind.Statements);
scriptSource.Execute(scope);

您可以将 类 添加到范围,就像使用 SetVariable 的变量一样。在 VB.Net:

Dim engine As Microsoft.Scripting.Hosting.ScriptEngine = IronPython.Hosting.Python.CreateEngine()
Dim scope As Microsoft.Scripting.Hosting.ScriptScope = engine.CreateScope()
scope.SetVariable("MyClass", IronPython.Runtime.Types.DynamicHelpers.GetPythonTypeFromType(GetType(MyClass)))
Dim source As Microsoft.Scripting.Hosting.ScriptSource = engine.CreateScriptSourceFromFile(pathToScript)
source.Execute(scope)