簡體   English   中英

如何構建 setup.py 以使用 Python、pybind11 和 Mingw-w64 編譯 C++ 擴展?

[英]How can I build a setup.py to compile C++ extension using Python, pybind11 and Mingw-w64?

我目前正在嘗試編寫一個“setup.py”腳本,當用戶安裝 python package 時,它會自動編譯與“pybind11”綁定的我的 C++ 擴展。 在 Windows 中,使用“VS19 MSVC”編譯器實現它沒有任何問題。 但如果用戶安裝了“MinGW-w64”,我會嘗試實現它。

這些是 package 文件:

**main.cpp**

    #include <pybind11/pybind11.h>
    
    int add(int i, int j) {
        return i + j;
    }
    
    namespace py = pybind11;
    
    PYBIND11_MODULE(pybind11_example, m) {
    
        m.def("add", &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。

請注意,我可以在運行Mingw-w64的情況下手動輕松地將**main.cpp**編譯為**pybind11_example.pyd**

    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,則在安裝 package 時自動將**main.cpp**編譯成**pybind11_example.pyd**需要手動制作嗎?

檢查這個問題的答案。 他們試圖解決相反的情況,強制使用 msvc 而不是 mingw,但是使用 setup.cfg 的方法可能會對您有所幫助。

這里的答案演示了如何根據設置工具的選擇指定命令行參數:如果是 msvc,則一組參數,另一組用於 mingw。

我相信第二種方法應該適合您的需要——無論安裝哪個編譯器,您都有正確的命令行來構建您的模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM