Cython转换.py为.pyd后导入报错PyInit_world不存在问题求助
Cython编译.pyd后导入报错解决方案
错误根因
ImportError: dynamic module does not define module export function (PyInit_world)错误在你的环境下通常由以下几个原因触发:
- 编译生成的.pyd文件架构和Python版本不匹配:你使用的是32位Python 3.7,若编译时调用了64位编译器工具链,生成的64位.pyd无法被32位Python识别导出函数
- 编译参数未适配Python3规范:Cython默认可能使用Python2的规则编译,导致导出函数命名不符合Python3的要求
- 编译输出的.pyd文件名不符合规范,或同目录下存在同名的.py文件优先被加载
解决步骤
按以下顺序操作即可解决问题:
- 首先确认你调用的Python环境为32位,执行命令验证:
python -c "import platform;print(platform.architecture())"
输出应为('32bit', 'WindowsPE'),若显示64位,需要切换到你安装的32位Python 3.7的执行路径
2. 修改setup.py代码,添加32位编译参数和Python3适配规则,修改后代码如下:
from setuptools import setup from Cython.Build import cythonize import sys extra_compile_args = [] extra_link_args = [] if sys.platform == 'win32': # 指定编译为32位程序 extra_compile_args.append('/arch:IA32') extra_link_args.append('/MACHINE:X86') setup( ext_modules = cythonize("world.py", compiler_directives={'language_level' : "3"}), options={ 'build_ext': { 'extra_compile_args': extra_compile_args, 'extra_link_args': extra_link_args } } )
- 清空之前编译生成的所有中间文件,包括build文件夹、world.c文件、旧的.pyd文件
- 打开32位VS编译工具终端:在开始菜单找到x86 Native Tools Command Prompt for VS 你的VS版本,在这个终端内执行后续操作,避免默认cmd调用64位编译器
- 执行编译命令:
python setup.py build_ext --inplace
- 编译完成后确认生成的.pyd文件名格式为
world.cp37-win32.pyd,不要修改文件名,将原world.py移动到其他目录后,在同目录执行import world即可正常运行
内容的提问来源于stack exchange,提问作者Dennis Asamoah
相关产品推荐
相关产品推荐

