0Pricing
C++ Academy · Lesson

Calling Python from C++ via pybind11

Wrap C++ code as a Python module using pybind11.

Calling Python from C++ via pybind11 is a free C++ Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why pybind11?

pybind11 is a header-only library that creates Python bindings for C++ code with minimal boilerplate. Used by SciPy, TensorFlow, and many other projects.

A Minimal Module

Define a Python module in a single file with the PYBIND11_MODULE macro.

#include <pybind11/pybind11.h>
namespace py = pybind11;

int add(int a, int b) { return a + b; }

PYBIND11_MODULE(mymodule, m) {
    m.def("add", &add, "Add two integers");
}

Building the Module

Build as a Python extension module — usually with CMake or setuptools.

# CMake
find_package(pybind11 REQUIRED)
pybind11_add_module(mymodule mymodule.cpp)

Using from Python

Import and use like any Python module.

# Python
import mymodule
print(mymodule.add(2, 3))   # 5

Exposing Classes

Use py::class_ to bind a C++ class. Constructors, methods, and properties all map to Python equivalents.

class Point {
public:
    Point(int x, int y) : x_(x), y_(y) {}
    int x() const { return x_; }
    int y() const { return y_; }
private:
    int x_, y_;
};

PYBIND11_MODULE(geom, m) {
    py::class_<Point>(m, "Point")
        .def(py::init<int, int>())
        .def("x", &Point::x)
        .def("y", &Point::y);
}

Type Conversions

pybind11 converts common types automatically:

  • std::string ↔ Python str
  • std::vector<T> ↔ Python list
  • std::map ↔ Python dict
  • Numerics ↔ Python int/float

NumPy Interop

Pass NumPy arrays as py::array_t<T>. Access the buffer for zero-copy operations.

void scale(py::array_t<double> arr, double factor) {
    auto buf = arr.mutable_unchecked<1>();
    for (size_t i = 0; i < buf.size(); ++i)
        buf(i) *= factor;
}

Lambdas as Bindings

Bind a lambda directly when you want to transform arguments or wrap behavior.

m.def("show", [](const Point& p) {
    return "(" + std::to_string(p.x()) + ", " + std::to_string(p.y()) + ")";
});

Releasing the GIL

For long C++ computations, release the GIL so other Python threads can run.

m.def("slow", []() {
    py::gil_scoped_release release;
    // expensive C++ work, no Python access
});

Performance

pybind11 adds minimal overhead — usually a few hundred nanoseconds per call. Negligible for non-trivial functions; matters in tight loops with cheap callees.

Alternatives

Other Python-C++ bridges:

  • Boost.Python — older, heavier
  • SWIG — supports many languages
  • nanobind — newer, faster than pybind11

Real-World Use Cases

pybind11 is ideal for:

  • Wrapping a C++ library for Python users
  • Speeding up Python hot paths with C++ code
  • Sharing numerical kernels between C++ apps and Python tools

Quick Check

Which macro does pybind11 use to declare a Python module?

Recap

pybind11 makes wrapping C++ for Python almost effortless. Declare modules with PYBIND11_MODULE, bind functions with m.def, and classes with py::class_. Built-in conversions cover STL types; NumPy arrays are zero-copy.

Frequently asked questions

Is the “Calling Python from C++ via pybind11” lesson free?

Yes — the full text of “Calling Python from C++ via pybind11” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “Calling Python from C++ via pybind11”?

Wrap C++ code as a Python module using pybind11. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Calling Python from C++ via pybind11” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Extern C and the C ABI
  2. Calling Python from C++ via pybind11
  3. C++ for Rust FFI Boundaries
  4. Using SWIG for Multi-Language Bindings
← Back to C++ Academy