我希望向 IronPython 运行时公开特定的 .Net 类型。我可以做这个:
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.Runtime.LoadAssembly(typeof(Program).Assembly); // current assembly with types
但这会将所有类型暴露给运行时。可以选择类型加载吗?
我希望向 IronPython 运行时公开特定的 .Net 类型。我可以做这个:
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.Runtime.LoadAssembly(typeof(Program).Assembly); // current assembly with types
但这会将所有类型暴露给运行时。可以选择类型加载吗?
实际上有几个选项都不是自动的。首先,您需要调用 DynamicHelpers.GetPythonTypeFromType(typeof(TypeToInject)) 以获取实际可用的 PythonType 对象。然后你可以:
将其注入 ScriptRuntime.Globals 即可导入
针对您将要运行的某些代码将其注入 ScriptScope
将其注入 PythonType.GetBuiltinModule() 范围,无需导入即可使用
不,您必须加载整个程序集。
这是由ScriptDomainManager内部管理的,它只保留加载程序集的列表,而不是类型。
最好的选择是让您的程序集仅公开您希望在 Python 环境中可用的类型,而将其余类型保留在内部。
您可以像这样在 C# 中公开单个对象:
ScriptScope scope = runtime.CreateScope(); //get a scope where we put in the stuff from the host
scope.SetVariable("lab", lab);
该对象在脚本中使用给定名称可用
lab.AnyMethodOfYourObject()