[英]How can I build manually C++ extension with mingw-w64, Python and pybind11?
[英]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**
需要手動制作嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.