python使用Pybind11扩展c++

Pybind11 是一个轻量级的C++ 库,旨在无缝地将C++代码绑定到Python。它简化了C++ 函数、类和数据结构在Python中使用的过程,使得开发人员可以方便地在Python中调用C++ 代码,同时保留两者的性能优势下面将详细介绍Pybind11的基本概念、安装方法、用法以及示例代码。

Pybind11的基本概念

Pybind11允许C++函数、类和其他对象暴露给Python,使得它们可以在Python中被直接调用。主要功能包括:

  • 暴露C++函数和类给Python。
  • 支持C++的STL容器和数据结构在Python中的使用。
  • 支持C++的异常传递到Python。
  • 允许使用Python对象和函数在C++中。

Pybind11 的优点

  • 兼容性强,支持 Python2.7、Python3.x、PyPy (PyPy2.7 >= 5.7);
  • 可以在 C++ 中使用 lambda 表达式,并在 Python 中使用捕获的变量;
  • 大量使用移动特性,保证数据转移时的性能;
  • 可以很方便地通过 Python buffer protocol 进行数据类型的转移;
  • 可以很方便地对函数进行向量化加速;
  • 支持使用 Python 的切片语法;
  • Pybind11 是 header-only 的,只需要包含头文件即可;
  • 相比于 Boost::Python,生成的二进制文件体积更小;
  • 函数签名通过 constexper 提前计算,进一步减小二进制文件体积;
  • C++ 中的类型可以很容易地进行序列化/反序列化;

Python 以其灵活和易于上手的特点,成为了当下炙手可热的编程语言。然而,动态解释型语言的特点限制了其性能。因此在需要性能的地方,往往使用 C、C++ 等传统高性能语言实现(如 numpy 这种科学计算库),并在 Python 中调用。这就是所谓的混合编程,发挥各自的优势,取长补短。

Pybind11出来以前,Python和C/C++混合编程

Python 的 C-API (Python.h)

SWIG

Python 的 ctypes 模块

Cython

Boost::Python

安装Pybind11

Pybind11可以通过pip轻松安装:

bash 复制代码
pip install pybind11

或者可以从源码安装:

bash 复制代码
git clone https://github.com/pybind/pybind11.git
cd pybind11
mkdir build
cd build
cmake ..
make install

用法示例

1. 暴露简单的C++函数

首先,创建一个简单的C++函数,然后使用Pybind11将其暴露给Python。

C++代码(example.cpp)

cpp 复制代码
#include <pybind11/pybind11.h>

// 简单的C++函数
int add(int i, int j) {
    return i + j;
}

// Pybind11模块定义
PYBIND11_MODULE(example, m) {
    m.def("add", &add, "A function which adds two numbers");
}

编译上面的代码:

bash 复制代码
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)

然后在Python中使用:

python 复制代码
import example
print(example.add(2, 3))  # 输出: 5
2. 暴露C++类

Pybind11还可以暴露C++类,并在Python中创建和操作这些类的实例。

C++代码(example.cpp)

cpp 复制代码
#include <pybind11/pybind11.h>

class Pet {
public:
    Pet(const std::string &name) : name(name) {}
    void setName(const std::string &name_) { name = name_; }
    std::string getName() const { return name; }
private:
    std::string name;
}

PYBIND11_MODULE(example, m) {
    pybind11::class_<Pet>(m, "Pet")
        .def(pybind11::init<const std::string &>())
        .def("setName", &Pet::setName)
        .def("getName", &Pet::getName);
}

编译代码:

bash 复制代码
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)

在Python中使用:

python 复制代码
import example
p = example.Pet("Mittens")
print(p.getName())  # 输出: Mittens
p.setName("Whiskers")
print(p.getName())  # 输出: Whiskers

更多功能

暴露STL容器

Pybind11可以将C++的STL容器(如std::vectorstd::map等)暴露给Python。

C++代码(example.cpp)

cpp 复制代码
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>

std::vector<int> get_vector() {
    return {1, 2, 3, 4, 5};
}

PYBIND11_MODULE(example, m) {
    m.def("get_vector", &get_vector);
}

编译代码:

bash 复制代码
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)

在Python中使用:

python 复制代码
import example
print(example.get_vector())  # 输出: [1, 2, 3, 4, 5]
异常处理

Pybind11支持将C++中的异常传递到Python,并在Python中进行处理。

C++代码(example.cpp)

cpp 复制代码
#include <pybind11/pybind11.h>

void throws_exception() {
    throw std::runtime_error("An error occurred!");
}

PYBIND11_MODULE(example, m) {
    m.def("throws_exception", &throws_exception);
}

编译代码:

bash 复制代码
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)

在Python中使用:

python 复制代码
import example

try:
    example.throws_exception()
except RuntimeError as e:
    print(e)  # 输出: An error occurred!

总结

Pybind11是一个强大且易于使用的工具,允许开发人员将C++ 代码无缝地集成到Python项目中。通过Pybind11,可以高效地暴露C++ 函数、类和数据结构,并在Python中进行调用和操作。其支持STL容器、异常处理等特性,使得它在C++ 与Python交互中表现得非常出色。使用Pybind11,可以充分利用C++的性能优势,同时享受Python的开发便利性。

相关推荐
FF-Studio2 分钟前
大语言模型(LLM)课程学习(Curriculum Learning)、数据课程(data curriculum)指南:从原理到实践
人工智能·python·深度学习·神经网络·机器学习·语言模型·自然语言处理
Sally璐璐12 分钟前
IPSAN 共享存储详解:架构、优化与落地实践指南
开发语言·php
Mr.Winter`18 分钟前
轨迹优化 | 基于激光雷达的欧氏距离场ESDF地图构建(附ROS C++仿真)
c++·人工智能·机器人·自动驾驶·ros·ros2·具身智能
csdn_aspnet20 分钟前
C++ n条水平平行线与m条垂直平行线相交的平行四边形的数量
c++
像风一样的男人@22 分钟前
python --货车装厢问题
开发语言·python
Humbunklung29 分钟前
Rust枚举:让数据类型告别单调乏味
开发语言·后端·rust
Y1nhl32 分钟前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
OEC小胖胖1 小时前
深入理解 Vue.js 响应式原理及其在 Web 前端开发中的应用
开发语言·前端·javascript·vue.js·web
qq_401700411 小时前
C语言中位运算以及获取低8位和高8位、高低位合并
c语言·开发语言·算法
yanjiaweiya1 小时前
云原生-集群管理
java·开发语言·云原生