SoFunction
Updated on 2025-05-07

Python uses Pybind11 to extend the implementation of c++

Pybind11 is a lightweight C++ library designed to seamlessly bind C++ code to Python. It simplifies the process of using C++ functions, classes and data structures in Python, allowing developers to easily call C++ code in Python, while retaining the performance advantages of both. Below is a detailed introduction to the basic concepts, installation methods, usage and sample code of Pybind11.

Basic concepts of Pybind11

Pybind11 allows C++ functions, classes, and other objects to be exposed to Python, so that they can be called directly in Python. Main functions include:

  • Expose C++ functions and classes to Python.
  • Supports the use of STL containers and data structures in Python.
  • C++-enabled exceptions are passed to Python.
  • Allows the use of Python objects and functions in C++.

Advantages of Pybind11

  • Strong compatibility, supports Python2.7, PyPy (PyPy2.7 >= 5.7);
  • You can use lambda expressions in C++ and use captured variables in Python;
  • Use a lot of mobile features to ensure performance during data transfer;
  • It is easy to transfer data types through Python buffer protocol;
  • It can easily accelerate the vectorization of functions;
  • Supports slicing syntax using Python;
  • Pybind11 is header-only, and only needs to include header files;
  • Compared to Boost::Python, the generated binary files are smaller;
  • Function signatures are calculated in advance through constexper to further reduce the binary file size;
  • Types in C++ can be easily serialized/deserialized;

Python has become a popular programming language today with its flexibility and ease of use. However, the characteristics of dynamic interpreted languages ​​limit their performance. Therefore, where performance is required, traditional high-performance languages ​​such as C and C++ are often implemented (such as scientific computing libraries such as numpy) and are called in Python. This is called hybrid programming, which uses their own strengths and complements their weaknesses.

Before Pybind11 came out, Python and C/C++ mixed programming

Python's C-API ()
SWIG
Python's ctypes module
Cython
Boost::Python

Install Pybind11

Pybind11 can be passedpipEasy installation:

pip install pybind11

Or you can install it from the source code:

git clone /pybind/
cd pybind11
mkdir build
cd build
cmake ..
make install

Usage example

1. Expose simple C++ functions

First, create a simple C++ function and then expose it to Python using Pybind11.

C++ code ()

#include <pybind11/>

// Simple C++ functionsint add(int i, int j) {
    return i + j;
}

// Pybind11 module definitionPYBIND11_MODULE(example, m) {
    ("add", &add, "A function which adds two numbers");
}

Compile the above code:

c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes)  -o example$(python3-config --extension-suffix)

Then use it in Python:

import example
print((2, 3))  # Output: 5

2. Expose C++ classes

Pybind11 can also expose C++ classes and create and manipulate instances of these classes in Python.

C++ code ()

#include <pybind11/>

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);
}

Compile the code:

c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes)  -o example$(python3-config --extension-suffix)

Use in Python:

import example
p = ("Mittens")
print(())  # Output: Mittens("Whiskers")
print(())  # Output: Whiskers

More features

Expose STL containers

Pybind11 can use C++ STL containers (such asstd::vectorstd::mapetc.) Expose to Python.

C++ code ()

#include <pybind11/>
#include <pybind11/>
#include <vector>

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

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

Compile the code:

c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes)  -o example$(python3-config --extension-suffix)

Use in Python:

import example
print(example.get_vector())  # Output: [1, 2, 3, 4, 5]

Exception handling

Pybind11 supports passing exceptions in C++ to Python and processing them in Python.

C++ code ()

#include <pybind11/>

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

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

Compile the code:

c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes)  -o example$(python3-config --extension-suffix)

Use in Python:

import example

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

Summarize

Pybind11 is a powerful and easy-to-use tool that allows developers to seamlessly integrate C++ code into Python projects. With Pybind11, C++ functions, classes, and data structures can be efficiently exposed, and calls and operations can be made in Python. It supports STL containers, exception handling and other features, making it perform very well in C++ and Python interaction. Using Pybind11, you can make full use of the performance advantages of C++ while enjoying the convenience of Python development.

This is the end of this article about the implementation of python using Pybind11 to extend c++. For more related content on Pybind11 to extend c++, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!