A Minimal pybind11 Example: Calling C++ from Python
Why This Matters
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
- pybind11 is the bridge between Python and C++
- You write C++ for speed-critical parts
- Add
PYBIND11_MODULEto expose it to Python - Compile once, use like normal Python
- 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
.soor.pydfile 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:
- Find a slow function in your Python code
- Rewrite just that function in C++
- Use pybind11 to connect it
- 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