python - 如何构建 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**
而无需手动制作?
解决方案
推荐阅读
- haskell - Haskell - 无法匹配预期类型
- ms-access - 访问表单的动态组合框问题
- android - 如果键在另一个对象内,如何使用 Retrofit 解析 Json
- javascript - JavaScript:提取数组中每个字符串的第一个字母?
- ios - three.js fontloader 在 ios 上不起作用
- sql - 如何在sql中将dd-mm-yyyy转换为DD-MON-yyyy
- hyperledger-fabric - 使用单独的 configtx.yaml 文件按顺序生成 genesis.block 和 channel.tx 时出错
- ios - 使用 Jenkins for iOS 设置构建 fastlane
- php - woocommerce 条件字段
- java - 带有 CheckedTextView 的列表视图无法正常工作