IronPython:使用 clr.AddReference() 导入模块时如何运行初始化代码?

发布于 2024-09-24 23:52:09 字数 128 浏览 1 评论 0原文

我想知道是否有一种方法可以让 init 代码在使用 clr.AddReference() 导入 .NET 程序集时运行,就像导入 python 文件执行 init.py 一样驻留在同一目录中的代码。提前致谢!

I was wondering if there was a way that you could get init code to run upon importing a .NET assembly using clr.AddReference(), in the same way that importing a python file executes the init.py code that resides in the same directory. Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

宁愿没拥抱 2024-10-01 23:52:09

据我所知,这是不可能的 clr.AddReference 。

如果您的程序集具有 IronPython 模块,则可以在导入该模块时运行代码(类似于 __init__.py)。 IronPython 模块的设置非常简单:

[assembly: PythonModule("mymodule", typeof(MyModule))]
public static class MyModule
{
    [SpecialName]
    public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
        // module initialization code
    }

    // variables, functions, classes, etc. that appear in the module
}

不要被名称中的“Reload”部分所迷惑;当模块加载时以及每次重新加载时都会调用它。

如果您的程序集将在 IronPython 之外使用,您可以将此模块放入引用原始模块的单独程序集中。如果您想要一些有关如何编写模块的示例,请查看 上的 IronPython.Modules 项目的源代码http://ironpython.codeplex.com

It's not possible from clr.AddReference, as far as I know.

If your assembly has an IronPython module, you can run code when it is imported (a la __init__.py). An IronPython module is pretty simple to set up:

[assembly: PythonModule("mymodule", typeof(MyModule))]
public static class MyModule
{
    [SpecialName]
    public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
        // module initialization code
    }

    // variables, functions, classes, etc. that appear in the module
}

Don't get confused by the "Reload" part of the name; it's called when the module is loaded as well as every time it is reloaded.

If your assembly will be used outside of IronPython, you can put this module in a separate assembly that references your original module. If you want some examples of how to write modules, check out the source to the IronPython.Modules project on http://ironpython.codeplex.com.

沦落红尘 2024-10-01 23:52:09

这是不可能的。

唯一的方法是更改​​ clr.AddReference 方法。由于 IronPython 是开源的,因此应该很容易。

It is not possible.

The only way is to change the clr.AddReference method. As IronPython is open source it should be easy.

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