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::vector、std::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的开发便利性。

相关推荐
如夏倾城27 分钟前
VRRP(虚拟路由器冗余协议Virtual Router Redundancy Protocol)
网络·python·网络协议·安全·智能路由器·负载均衡·信息与通信
小七在进步33 分钟前
string的实现(1)
c++·笔记·visual studio
IvanCodes1 小时前
LangChain(04):Runnable 与 LCEL 的执行与组合机制
python·langchain·agent
特创数字科技1 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
布莱克6052 小时前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环
东莞市云毅网络有限公司2 小时前
用 Playwright 搭一套问答平台引用监测的最小骨架
python·数据清洗·rag·企业知识库·文档解析
Thanks_ks2 小时前
【第 010 讲】全面掌握 Python 变量与常量:变量的定义与赋值 | 标识符与命名规范 | 变量的底层机制 | 常量与魔术数字
python·内存·变量·标识符·常量·赋值·命名规范
敲上瘾3 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
联犀3 小时前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
飞Link3 小时前
灵巧手是什么?从机械结构、驱动方式到控制原理,认识机器人的精细操作能力
人工智能·python·机器人