有没有办法从 C# 代码使用 IronPython 对象和函数(编译成程序集)?

发布于 2024-09-24 22:07:22 字数 52 浏览 15 评论 0 原文

IronPython.net 文档称程序集中的 MSIL 不符合 CLS,但有解决方法吗?

IronPython.net documentation says the MSIL in the assembly isn't CLS-compliant, but is there a workaround?

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

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

发布评论

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

评论(2

递刀给你 2024-10-01 22:07:22

这在一定程度上是向 C# 4.0 添加动态类型的动机。最大的问题是 IronPython 声明不包含类型信息,这使得在 C# 中使用它变得困难。 dynamic 关键字向 C# 4.0 添加了对此类动态类型对象的支持。例如,请参见:

从 C# 3.0 调用函数/对象有点烦人,但它 的内容,而不是仅仅编写 foo.Bar(42)

This was partly a motivation for adding the dynamic type to C# 4.0. The biggest problem is that IronPython declarations doesn't include type information, which makes it difficult to use it from C#. The dynamic keyword adds support for such dynamically typed objects to C# 4.0. See for example:

Calling functions/objects from C# 3.0 is a bit more annoying, but it is still possible. You'll just have to write something like foo.Invoke("Bar", 42) instead of just writing foo.Bar(42).

ら栖息 2024-10-01 22:07:22

我正在手机上输入此内容,因此请原谅任何愚蠢的错误。要使用已编译的程序集,请确保使用 clr.CompileModules 进行编译,而不是 pyc.py。然后在 C# 中调用 Python ScriptEngine 对象的 LoadAssembly 方法。然后可以通过调用 ScriptEngine 上的 ImportModule 方法来导入该模块。如果您可以从那里利用动态关键字,请这样做。否则,您将被一些对 GetVariable 的神奇字符串大量调用所困扰。另请注意,您必须以一种或另一种形式向编译后的 Python 程序集提供标准库。

I'm typing this on my phone so please forgive any silly mistakes. To use the compiled assembly, make sure you compile with clr.CompileModules, NOT pyc.py. Then in your C# call the LoadAssembly method on your Python ScriptEngine object. The module can then be imported by calling the ImportModule method on your ScriptEngine. From there if you can take advantage of the dynamic keyword, do so. Otherwise you'll be stuck with some magic string heavy calls to GetVariable. Also note that you'll have to provide the standard library to your compiled Python Assembly in one form or another.

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