python - 使用 Cython 进行扩展,名称与源文件不同

标签 python gcc cython

我知道如何使用 cythonize -o mymodule.c mymodule.py 或使用 cython 命令从 Python 生成 C 代码。生成的 C 文件必须使用 gcc 或任何其他 C 编译器编译为 Python 扩展,我也可以这样做。如果我想要它真的很简单,我只使用 distutils/setuptoolspython setup.py build_ext

但我想不通的是如何制作一个名称与源文件不同 的扩展文件 (pyd/so)。我不能简单地重命名文件,因为扩展中必须有一个函数 PyInit_modulename,而且我不能将 modulename.pyd 更改为 _modulename.pyd,这将需要 PyInit__modulename 并抛出此异常:

ImportError: dynamic module does not define init function (PyInit__modulename)

基本上应该是这样的:

mymodule.py -> _mymodule.pyd

这避免了例如如果我有两个名称相同但结尾不同的文件 (py/pyd/pyc/pyo/so/dll),导入混淆:

mydir/
  mymodule.py
  mymodule.pyd

代码:

from mymodule import func
func()
# Is this now from the extension or from the python code?
# And how to access tho other one?

我需要的是:

mydir/
  mymodule.py
  _mymodule.pyd   <- Note the underscore!

代码:

import mymodule as script
script.func()
# Run the code from the python file

import _mymodule as extension
extension.func()
# Run code from the extension

但是我到底怎么才能这样编译呢?

提前致谢!


我只有一个想法:我认为我需要从使用 cython 生成 C 代码的某个地方开始。

最佳答案

在您的 setup.py 中试试这个

try:
    from setuptools import setup
    from setuptools import Extension
except ImportError:
    from distutils.core import setup
    from distutils.extension import Extension

from Cython.Distutils import build_ext
import numpy as np # if it requires numpy

ext_modules = [Extension("desired_name",["original_name.pyx"])]

setup(
    name= 'Generic model class',
    cmdclass = {'build_ext': build_ext},
    include_dirs = [np.get_include()], # only if it requires numpy
    ext_modules = ext_modules)

关于python - 使用 Cython 进行扩展,名称与源文件不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38184272/

相关文章:

python - Tkinter 将文本调整为内容

python - 提高 pandas 中日期时间比较的性能

linux - linux ubuntu 16 32bit 上,DrPaulcarter 汇编语言教程,undefined reference 错误

c++ - 命名空间与包含的类同名,gcc 可以,clang 不行

python - 了解使用 Cython 扩展类型与 Python 类的好处

python - 如何导入 Bokeh 调色板

python - anaconda 中的 Numba 模块为空

c++ - 不是最后一个模板参数的推导和参数包 : is this valid code?

python - 我可以将这种并行迭代器模式与 Cython 一起使用吗?

python - 与 Cython 并行迭代列表