Cython生成.pyd文件后导入报错:PyInit_helloWorld未定义
问题分析
这个错误是因为编译生成的C扩展模块未定义Python 3要求的模块初始化函数PyInit_helloWorld,通常由源文件命名冲突、旧版构建方式兼容性问题或语言版本配置未生效导致。
解决步骤
1. 重命名源文件为Cython标准后缀
将原helloWorld.py重命名为helloWorld.pyx——这是Cython的标准源文件格式,既避免和生成的.pyd模块重名混淆,也能让Cython更明确地处理代码。
修改后的helloWorld.pyx内容不变:
import time def printHW(): print("Hello World - today's date is %s"%time.strftime('%Y-%m-%d',time.localtime())) if __name__ == '__main__': printHW()
2. 更新setup.py为官方推荐的构建方式
使用Cython官方推荐的cythonize函数替代旧的build_ext方式,确保Python 3的初始化函数正确生成:
try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize # 配置扩展模块,明确指定Python 3语言级别 ext_modules = cythonize( Extension( name="helloWorld", sources=["helloWorld.pyx"], language_level="3" ) ) setup( name='helloWorld', ext_modules=ext_modules )
3. 重新编译并测试
执行编译命令:
python setup.py build_ext --inplace
编译完成后,确保目录下存在helloWorld.pyd(Windows)或helloWorld.so(Linux/macOS),然后在Python环境中测试导入:
from helloWorld import printHW printHW()
额外注意事项
- 编译前可删除旧的
build目录和helloWorld.c文件,避免缓存影响 - 确保使用支持Python 3的Cython版本(建议安装最新稳定版:
pip install --upgrade cython) - 若仍有问题,检查生成的
helloWorld.c文件中是否存在PyInit_helloWorld函数;若不存在,可在.pyx文件顶部添加强制配置注释:# cython: language_level=3
内容的提问来源于stack exchange,提问作者Salvatore
相关产品推荐
相关产品推荐

