← Back to list

A Minimal pybind11 Example: Calling C++ from Python

Why This Matters

Manish Sri Sai Surya Routhu · 2026-01-22 21:59 · 0 claps · 2.7 min read
#pybind11 #python-libraries #c-libraries
Open on Medium ↗

A Minimal pybind11 Example: Calling C++ from Python

Why This Matters

Python is easy to write but can be slow. C++ is fast but harder to write. By combining them, you get:

  • Easy Python code for most of your program
  • Fast C++ code for the heavy calculations

This technique powers:

  • Machine learning frameworks (TensorFlow, PyTorch)
  • Scientific computing (NumPy, SciPy)
  • Game engines
  • High-frequency trading systems

How It Works: The Big Picture

Simple analogy: Python is your friendly waiter, C++ is the super-fast kitchen, and pybind11 is the order system connecting them.

The Complete Process

Practical Example: Fast Math Calculator

Let’s build a simple calculator that multiplies numbers super fast.

Step 1: Install pybind11

pip install pybind11

Step 2: Create C++ Code (calculator.cpp)

#include <pybind11/pybind11.h>
namespace py = pybind11;
// A simple function that multiplies two numbers
int multiply(int a, int b) {
    return a * b;
}
// A function that adds numbers in a range
int sum_range(int start, int end) {
    int total = 0;
    for (int i = start; i <= end; i++) {
        total += i;
    }
    return total;
}
// This connects C++ to Python
PYBIND11_MODULE(calculator, m) {
    m.doc() = "Fast calculator module";

    m.def("multiply", &multiply, "Multiply two numbers");
    m.def("sum_range", &sum_range, "Sum numbers in a range");
}

What’s happening here?

Step 3: Create Setup File (setup.py)

from setuptools import setup, Extension
import pybind11

# Tell Python how to build your C++ code
ext_modules = [
    Extension(
        'calculator',              # Module name
        ['calculator.cpp'],        # Your C++ file
        include_dirs=[pybind11.get_include()],
        language='c++',
    ),
]
setup(
    name='calculator',
    ext_modules=ext_modules,
)

Step 4: Compile It

python setup.py build_ext --inplace

This creates a file like calculator.so (Linux/Mac) or calculator.pyd (Windows).

Step 5: Use It in Python!

# Import your C++ module like any Python module
import calculator
# Use the C++ functions
result = calculator.multiply(5, 10)
print(f"5 × 10 = {result}")
# This runs super fast in C++
total = calculator.sum_range(1, 1000000)
print(f"Sum 1 to 1,000,000 = {total}")

The Data Flow

When to Use This

Use C++ for:

  • Heavy number crunching
  • Processing large data
  • Real-time calculations
  • Tight loops

Keep in Python:

  • File operations
  • Simple logic
  • User interface
  • Quick prototypes

Key Takeaways

  1. pybind11 is the bridge between Python and C++
  2. You write C++ for speed-critical parts
  3. Add PYBIND11_MODULE to expose it to Python
  4. Compile once, use like normal Python
  5. Best of both worlds: Python’s ease + C++’s speed

Common Issues

Import Error?

  • Make sure you compiled: python setup.py build_ext --inplace
  • Check the .so or .pyd file is in the same folder

Compilation Failed?

  • Install a C++ compiler (Visual Studio on Windows, Xcode on Mac)
  • Check pybind11 is installed: pip install pybind11

Next Steps

Start small:

  1. Find a slow function in your Python code
  2. Rewrite just that function in C++
  3. Use pybind11 to connect it
  4. Measure the speedup!

The first integration is always the hardest. After that, you’ll see 10x, 50x, even 100x speedups on the right tasks.

Questions? Drop a comment below! Want to see more advanced examples? Let me know what you’d like to learn.


메타데이터
post_id
61352b8306da
slug
a-minimal-pybind11-example-calling-c-from-python-61352b8306da
url
https://medium.com/@manish.surya.r/a-minimal-pybind11-example-calling-c-from-python-61352b8306da
canonical_url
https://medium.com/@manish.surya.r/a-minimal-pybind11-example-calling-c-from-python-61352b8306da
author_url
https://medium.com/@manish.surya.r
status
ok
fetched_at
2026-07-14 19:08:56