Skip to main content
 首页 » 编程设计

python之Cython 导入错误

2024年10月25日13thcjp

以下文件为 helloworld.pyx:

print("Hello World") 

以下文件为 setup.py:

from distutils.core import setup 
from distutils.extension import Extension 
from Cython.Distutils import build_ext 
ext_modules = [Extension("helloworld",["helloworld.pyx"] 
setup( 
    name = 'HW', 
    cmdclass = {'build_ext': build_ext}, 
    ext_modules = ext_modules 
) 

在我使用 python setup.py build_ext --inplace 之后,我得到了我的 *.so 文件

因此,我将 *.so 重命名为 hw.so,以获得更短的导入名称。

但是如果我启动 python 并输入:import hw 我得到这个错误:

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

大约 3 小时前我正在做同样的事情,一切正常。但我从这边尝试了一些东西:http://sourceforge.net/p/ubertooth/mailman/message/31699880/

我尝试了以下方法:

cmake -DPYTHON_EXECUTABLE=$(which python2) \ 
-DPYTHON_INCLUDE_DIR=$(echo /usr/include/python2*) \ 
-DPYTHON_LIBRARY=$(echo /usr/lib/libpython2.*.so) \ 

因为我想修理一些东西。我用“3”替换了所有“2”,因为我正在使用 python3.4

在我做了这个之后,我总是得到上面的错误。我破坏了任何路径吗?我怎样才能撤销它?谢谢你的帮助

请您参考如下方法:

在查看有关“使用 C 或 C++ 扩展 Python”的 Python 3 文档时,我们看到了这一点

The initialization function must be named PyInit_name(), where name is the name of the module, and should be the only non-static item defined in the module file.

( https://docs.python.org/3/extending/extending.html#the-module-s-method-table-and-initialization-function )

这意味着我们不能只更改模块的文件名而不更改 init 函数。我们必须首先使用最终名称编译模块。编译后重命名 .so 文件将不起作用。