本文共 2030 字,大约阅读时间需要 6 分钟。
pybind11 是一个强大的跨语言绑定库,允许 C++ 和 Python 互相调用。以下是在 Windows 10 上使用 pybind11 的详细指南,包括安装、编译和配置。
Python 2.7:确保系统安装了 Python 2.7 或更高版本。建议使用 Python 3.5 或更高版本。
pybind11 v2.3.dev0 或更高版本:从 GitHub 克隆最新版本。
安装 pytest:用于测试和验证绑定库。
pip install pytest
git clone https://github.com/pybind/pybind11.gitcd pybind11
mkdir buildcd build
cmake-gui ..
在 CMake 界面中,设置以下选项:
PYBIND11_CPP_STANDARD:选择 std:c++11 或 std:c++14(默认值)。PYTHON_EXECUTABLE:设置 Python 的路径,例如 C:/Python27/python.exe。CMAKE_INSTALL_PREFIX:指定安装目录,如 C:/Program Files/pybind11。PYBIND11_ENABLE_STATIC:建议启用静态库以减小依赖大小。cmake --build . cmake --install .
构建完成后,项目结构如下:
.├── include│ └── pybind11│ ├── attr.h│ ├── buffer_info.h│ └── ... (其他源文件)└── share └── cmake └── pybind11 ├── FindPythonLibsNew.cmake └── pybind11Config.cmake
在你的 C++ 代码中添加以下内容:
#includeusing namespace py::bind;
在 CMakeLists.txt 中添加以下内容:
add_library(examplelib MODULE example.cpp)target_link_libraries(examplelib pybind11::module)
#include "pybind11.h"using namespace py::bind;PYBIND11_MODULE(examplelib, m) { m.def("add", &add, "A function which adds two numbers", py::arg("i") = 1, py::arg("j") = 2); m.attr("the_answer") = 42; py::object world = py::cast("World"); m.attr("what") = world; py::class_(m, "Pet") .def(py::init()) .def("setName", &Pet::setName) .def("getName", &Pet::getName);} 在 Python 中使用:
import examplelib# 使用示例函数result = examplelib.add(1, 2)print(result) # 输出:3# 使用类pet = examplelib.Pet("Kzl")print(pet.getName()) # 输出:Kzl# 使用常数print(examplelib.the_answer) # 输出:42print(examplelib.what) # 输出:World 错误:无法找到 Python 的路径:确保 PYTHON_EXECUTABLE 在 CMake 配置中正确设置。
错误:缺少依赖项:确保安装了所有依赖的 C++ 库和 Python 绝对路径。
错误:动态加载错误:如果出现 Failed to load the python DLL 错误,检查 Python 安装路径是否正确。
通过以上步骤,你已经成功在 Windows 10 上配置并使用 pybind11 将 C++ 和 Python 接口。这个过程适合新手和开发者,帮助你快速上手 pybind11 的使用。
转载地址:http://gjjg.baihongyu.com/