Pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, primarily aimed at creating Python bindings for C++ code. It allows seamless integration of C++ with Python, which is particularly useful for computational tasks that require performance optimization. This guide will demonstrate how to call C++ code from Python using Pybind11.
# Include pybind11 headers
#include <pybind11/pybind11.h>
// A simple C++ function
int add(int a, int b) {
return a + b;
}
// Create a Python module
PYBIND11_MODULE(example, m) {
m.def("add", &add, "A function that adds two numbers");
}
To compile the C++ code into a Python module, you would typically use a setup script as follows:
from setuptools import setup, Extension
import pybind11
module = Extension('example', sources=['example.cpp'], include_dirs=[pybind11.get_include()])
setup(
name='example',
ext_modules=[module],
)
Building the module can be done using the following command:
python setup.py build_ext --inplace
Once built, you can use the module in Python like this:
import example
result = example.add(1, 2)
print(result) # Output: 3
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?