IronPython 将 .Net 类型暴露给运行时引擎
我希望向 IronPython 运行时公开特定的 .Net 类型。我可以这样做:
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.Runtime.LoadAssembly(typeof(Program).Assembly); // current assembly with types
但这会将所有类型暴露给运行时。可以选择性类型加载吗?
I'm looking to expose specific .Net types to the IronPython runtime. I can do this:
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.Runtime.LoadAssembly(typeof(Program).Assembly); // current assembly with types
But that exposes all types to the runtime. Is selective type loading possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上有一些选项,但它们都不是自动的。首先,您需要调用 DynamicHelpers.GetPythonTypeFromType(typeof(TypeToInject)) 来获取实际可用的 PythonType 对象。然后您可以:
将其注入到 ScriptRuntime.Globals 中,并且可用于导入
将其注入到针对某些对象的 ScriptScope 中您将要运行的代码
将其注入到 PythonType.GetBuiltinModule() 作用域中,无需导入即可使用
There are actually a few options none of them automatic though. First you'll need to call DynamicHelpers.GetPythonTypeFromType(typeof(TypeToInject)) to get a PythonType object which will actually be usable. Then you can either:
Inject it into ScriptRuntime.Globals and it'll be available for import
Inject it into a ScriptScope against some code you're going to be running
Inject it into the PythonType.GetBuiltinModule() scope and it'll be available w/o importing
不,您必须加载整个程序集。
这是由 ScriptDomainManager 内部管理的,它只保留以下列表:加载程序集,而不是类型。
最好的选择是让您的程序集仅公开您希望在 Python 环境中可用的类型,并将其余类型保留在内部。
No, you must load the entire assembly.
This is internally managed by the ScriptDomainManager, which only keeps a list of loaded assemblies, not types.
The best option would be to make your assembly only expose the types publicly that you want available within your Python environment, and leave the rest of the types internal.
您可以在 C# 中公开单个对象,如下所示:
该对象在使用给定名称的脚本中可用
You can expose a single object in C# like so:
The object is the available in the script using the given name