【问题标题】:Call IronPython from standard Python从标准 Python 调用 IronPython
【发布时间】:2016-02-04 12:32:02
【问题描述】:

如何在 Python 中调用 IronPython 函数?有没有一种简单的方法来连接两者。我需要 IronPython 中没有的一整套适当的 Python 库和 Python .net 目前没有的最新 CLR 的灵活性。

到目前为止,我尝试的是编译 IronPython dll,但无法在 Python 中正确加载它。

我尝试让 IronPython n 可以从 Python 中调用

foo.py

def foo():
    print 'hello world'

compile_ipy.py

import clr
clr.CompileModules("foo.dll", "foo.py")

我尝试从 Python 调用 Iron Python

call_ipy_from_py1.py

import ctypes
dll = ctypes.WindDLL('foo.dll')
dll.foo() # AttributeError: function 'foo' not found

call_ipy_from_py2.py

import ctypes
dll = ctypes.cdll.LoadLibrary('foo.dll')
dll.foo() # AttributeError: function 'foo' not found

【问题讨论】:

  • 你能举个简单的例子吗?
  • @PeterWood 让我们从 Python 调用一个在 IronPython 中打印 hello world 的函数开始,我将包括我尝试过的内容。

标签: python .net interop ironpython python.net


【解决方案1】:

.NET DLL 与 C DLL 不同(您可以通过 ctypes 使用)。但是,您可以使用 Python.NET 库来调用函数,如下所示:

import clr # Imports Python.Runtime.dll
import foo # Imports foo.dll
foo.foo()

我不知道您所说的“Python .net 当前没有的最新 CLR”是什么意思。您可以使用此处提供的版本:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pythonnet 如果您需要使用 CPython 3,我将它与 .NET 4.5.1 库一起使用没有问题。

【讨论】:

  • 我不知道这些二进制文件,但是当我import clr 以这种方式安装时出现以下错误ImportError: DLL load failed: %1 is not a valid Win32 application.
  • 还在 pythonnet 源页面上,他们将 clr 4.0 列为最新版本,sourceforge.net/projects/pythonnet/files
  • 关于第一条评论:这通常意味着它找不到 DLL 或者您安装了错误的 DLL(即 32 位系统上的 64 位)。 Python.Runtime.dllclr.pyd 在您的 site-packages 目录中吗?
  • 关于第二个:该页面严重过时,因为该项目有点被放弃了。开发在这里持续了一段时间:github.com/pythonnet/pythonnet 和这里(对于 Python 3):github.com/renshawbay/pythonnet
  • 啊我现在可以正常工作了,它与我的 Python 根目录中的另一个 clr.pyd 冲突
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多