Cythonized python.net 代码找不到系统程序集

Cythonized python.net code cannot find system assemblies

当我编译使用 python.net 访问 .Net 程序集的 python 代码时,它找不到那些程序集。没有编译它工作正常。

对于演示代码,我使用了https://github.com/pythonnet/pythonnet/blob/master/demo/helloform.py

我的setup.py文件

from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize

ext_modules = [
    Extension(
        'helloform',
        sources = ['helloform.py'],
        language = 'c++'
      )
]

setup(
  name = 'helloform',
  ext_modules = cythonize(ext_modules),
)

然后我用python setup.py build_ext --inplace构建它。

我想使用 import helloform 从 Python 提示加载已编译的模块,但失败了

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "helloform.py", line 8, in init helloform
ModuleNotFoundError: No module named 'System'

此答案未经测试 - 我不认为我可以轻松地设置一个环境来测试所以它有点猜测。如果它不起作用,我会删除它。

这可能是一个错误,如果您希望长期修复它,您 should report it. Cython does try to be compatible with Python wherever possible.... A quick investigate suggests that Python.NET overrides the built-in __import__ function. Cython looks to lookup and use this function in Python 2, but not in Python 3. This is no longer the preferred way of customizing import behaviour(但仍受支持)。我猜它会在 Cython + Python 2?

中工作

作为一种变通方法,您应该只 运行 Python 中的导入语句。有两种明显的方法可以做到这一点:

  1. 编写一个单独的小模块,仅包含导入语句,然后在 Cython 中从该模块导入:

    from import_module import WinForms, Size, Point
    
  2. 运行 exec 中的导入语句;从传递给它的全局字典中提取值:

    import_dict = {}
    exec("""import clr
    # etc...
    """, import_dict) # pass a dict in as `globals`
    WinForms = import_dict['WinForms']
    # etc.