首页 > 解决方案 > 如何构建 setup.py 以使用 Python、pybind11 和 Mingw-w64 编译 C++ 扩展?

问题描述

我目前正在尝试编写一个“setup.py”脚本,当用户安装 python 包时,它会自动编译与“pybind11”绑定的 C++ 扩展。在 Windows 中,使用“VS19 MSVC”编译器没有任何问题。但是如果用户安装了“MinGW-w64”,我会尝试实现它。

这些是包文件:

**main.cpp**

    #include <pybind11/pybind11.h>
    
    int add(int i, int j) {
        返回 i + j;
    }
    
    命名空间 py = pybind11;
    
    PYBIND11_MODULE(pybind11_example, m) {
    
        m.def("添加", &add);
    }
**setup.py**

    from setuptools import setup, Extension
    import pybind11
    
    ext_modules = [
        Extension(
            'pybind11_example',
            sources = ['main.cpp'],
            include_dirs=[pybind11.get_include()],
            language='c++'
        ),
    ]
    
    setup(
        name='pybind11_example',
        ext_modules=ext_modules
    )

将这两个文件放在同一个文件夹中并从命令提示符运行:

    python setup.py build

如果用户VS19 MSVC安装了编译器,它会成功生成**pybind11_example.pyd**可以测试以与 python 一起运行的代码:

    import pybind11_example as m
    print(m.add(1, 2))

但是,如果用户Mingw-w64安装了编译器,则会引发错误,指出需要 Visual Studio 2015。

请注意,我可以通过运行轻松地**main.cpp**手动**pybind11_example.pyd**编译Mingw-w64

    g++ -static -shared -std=c++11 -DMS_WIN64 -fPIC -I C:\...\Python\Python38\Lib\site-packages\pybind11\include -I C:\ ... \Python\Python38\include -L C:\ ... \Python\Python38\libs main.cpp -o pybind11_example.pyd -lPython38

有没有办法以一种方式编写**setup.py**,如果用户在安装软件包时使用带有MinGW-w64编译器的 Windows 自动编译**main.cpp****pybind11_example.pyd**而无需手动制作?

标签: pythonc++mingw-w64distutilspybind11

解决方案


这个问题的答案。他们试图解决相反的情况,强制使用 msvc 而不是 mingw,但 setup.cfg 的方法可能会对您有所帮助。

这里的答案演示如何根据设置工具所做的选择来指定命令行参数:如果是 msvc,则一组参数,另一组用于 mingw。

我相信第二种方法应该满足您的需求 - 无论安装了哪个编译器,您都有正确的命令行来构建您的模块。


推荐阅读