IronPython 将 .Net 类型暴露给运行时引擎

发布于 2024-08-20 14:10:58 字数 290 浏览 2 评论 0原文

我希望向 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

何必那么矫情 2024-08-27 14:10:58

实际上有一些选项,但它们都不是自动的。首先,您需要调用 DynamicHelpers.GetPythonTypeFromType(typeof(TypeToInject)) 来获取实际可用的 PythonType 对象。然后您可以:

  1. 将其注入到 ScriptRuntime.Globals 中,并且可用于导入

  2. 将其注入到针对某些对象的 ScriptScope 中您将要运行的代码

  3. 将其注入到 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:

  1. Inject it into ScriptRuntime.Globals and it'll be available for import

  2. Inject it into a ScriptScope against some code you're going to be running

  3. Inject it into the PythonType.GetBuiltinModule() scope and it'll be available w/o importing

另类 2024-08-27 14:10:58

不,您必须加载整个程序集。

这是由 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.

ぺ禁宫浮华殁 2024-08-27 14:10:58

您可以在 C# 中公开单个对象,如下所示:

ScriptScope scope = runtime.CreateScope(); //get a scope where we put in the stuff from the host
scope.SetVariable("lab", lab);

该对象在使用给定名称的脚本中可用

lab.AnyMethodOfYourObject()

You can expose a single object in C# like so:

ScriptScope scope = runtime.CreateScope(); //get a scope where we put in the stuff from the host
scope.SetVariable("lab", lab);

The object is the available in the script using the given name

lab.AnyMethodOfYourObject()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文