如何修复 Python CFFI 错误 LNK2001: unresolved external symbol PyInit__...

问题:

尝试在 Windows 上使用 C 模块安装 Python 库时,你看到类似这样的错误消息

error.txt
LINK : error LNK2001: unresolved external symbol PyInit__cv_algorithms
build\temp.win-amd64-3.6\Release\src_cv_algorithms.cp36-win_amd64.lib : fatal error LNK1120: 1 unresolved externals
error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe' failed with exit status 1120

解决方案

在 Windows 上,CFFI 没有正确生成。

你可以通过添加模板函数并仅在 Windows 上包含它来轻松修复:我建议像这样创建 windows.cpp

windows.cpp
/**
 * 这包含使 Windows 上安装工作的技巧。
 * 这修复错误 LNK2001: unresolved external symbol PyInit__cv_algorithms
 */
void PyInit__cv_algorithms(void) { }

**从错误消息中复制并粘贴函数名称!**如果使用错误的函数名称,修复将不起作用。

如何仅在 Windows 上包含该文件的示例:

setup.py
platform_src = ["src/windows.cpp"] if os.name == 'nt' else []

mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms',
                         sources=['src/main.cpp'] + platform_src)

有关完整示例,请参见 cv_algorithms,我首次在那里实现了此修复。


Check out similar posts by category: Python