### Install pybind11 from Source Source: https://pybind11.readthedocs.io/en/latest/compiling.html Commands to build and install the pybind11 repository for system-wide availability. ```bash # Classic CMake cd pybind11 mkdir build cd build cmake .. make install # CMake 3.15+ cd pybind11 cmake -S . -B build cmake --build build -j 2 # Build on 2 cores cmake --install build ``` -------------------------------- ### Setup pybind11 extension with setuptools Source: https://pybind11.readthedocs.io/en/latest/compiling.html Basic configuration for building a pybind11 extension using setup_helpers. ```python from glob import glob from setuptools import setup from pybind11.setup_helpers import Pybind11Extension ext_modules = [ Pybind11Extension( "python_example", sorted(glob("src/*.cpp")), # Sort source files for reproducibility ), ] setup(..., ext_modules=ext_modules) ``` -------------------------------- ### Install pybind11 via vcpkg Source: https://pybind11.readthedocs.io/en/latest/installing.html Use the Microsoft vcpkg dependency manager to clone the repository and install the pybind11 port. ```bash git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install vcpkg install pybind11 ``` -------------------------------- ### Import local Python files Source: https://pybind11.readthedocs.io/en/latest/advanced/embedding.html Example of a local Python module and how to import and use it from C++. ```python """calc.py located in the working directory""" def add(i, j): return i + j ``` ```cpp py::module_ calc = py::module_::import("calc"); py::object result = calc.attr("add")(1, 2); int n = result.cast(); assert(n == 3); ``` -------------------------------- ### Install pybind11 via PyPI Source: https://pybind11.readthedocs.io/en/latest/installing.html Install the pybind11 package using pip. The global variant is intended for virtual environments or project configuration files. ```bash pip install pybind11 ``` ```bash pip install "pybind11[global]" ``` -------------------------------- ### Compile and test on Linux/macOS Source: https://pybind11.readthedocs.io/en/latest/basics.html Use these commands to build and verify the library on Unix-like systems after installing prerequisites. ```bash mkdir build cd build cmake .. make check -j 4 ``` -------------------------------- ### Example top command output Source: https://pybind11.readthedocs.io/en/latest/faq.html Sample output showing the RES column used to track memory consumption. ```text PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1266095 rwgk 20 0 5207496 611372 45696 R 100.0 0.3 0:08.01 test_type_caste ``` -------------------------------- ### Install pybind11 via Homebrew Source: https://pybind11.readthedocs.io/en/latest/installing.html Install the pybind11 package on macOS or Linux using the Homebrew package manager. ```bash brew install pybind11 ``` -------------------------------- ### Integrate pybind11 using find_package Source: https://pybind11.readthedocs.io/en/latest/compiling.html Basic setup for a CMake project that uses an installed version of pybind11. ```cmake cmake_minimum_required(VERSION 3.15...4.2) project(example LANGUAGES CXX) find_package(pybind11 REQUIRED) pybind11_add_module(example example.cpp) ``` -------------------------------- ### Install pybind11 via conda-forge Source: https://pybind11.readthedocs.io/en/latest/installing.html Install the library using the conda package manager from the conda-forge channel. ```bash conda install -c conda-forge pybind11 ``` -------------------------------- ### Create a pybind11 module Source: https://pybind11.readthedocs.io/en/latest/basics.html Full example of a C++ file defining a module and exposing a function using the PYBIND11_MODULE macro. ```cpp #include namespace py = pybind11; int add(int i, int j) { return i + j; } PYBIND11_MODULE(example, m, py::mod_gil_not_used()) { m.doc() = "pybind11 example plugin"; // optional module docstring m.def("add", &add, "A function that adds two numbers"); } ``` -------------------------------- ### Verify Inheritance in Python Source: https://pybind11.readthedocs.io/en/latest/classes.html Example usage demonstrating that derived instances expose base class fields and derived methods. ```python >>> p = example.Dog("Molly") >>> p.name 'Molly' >>> p.bark() 'woof!' ``` -------------------------------- ### Find pybind11 package Source: https://pybind11.readthedocs.io/en/latest/cmake/index.html Examples of finding the pybind11 package with and without version requirements. ```cmake find_package(pybind11 CONFIG) find_package(pybind11 2.9 EXACT CONFIG REQUIRED) ``` -------------------------------- ### Using the ostream_redirect context manager in Python Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/utilities.html Example of using the generated context manager to capture output in Python code. ```python with ostream_redirect(stdout=True, stderr=True): noisy_function() ``` -------------------------------- ### Configure native_enum with Docstring Source: https://pybind11.readthedocs.io/en/latest/classes.html Example of providing a custom docstring to the native_enum constructor. ```cpp py::native_enum(pet, "Kind", "enum.IntEnum", "Constant specifying the kind of pet") ``` -------------------------------- ### Demonstrate noconvert behavior with custom class Source: https://pybind11.readthedocs.io/en/latest/advanced/functions.html Example showing how a custom class implementing __float__ behaves when passed to functions with and without noconvert. ```python class MyFloat: def __init__(self, value: float) -> None: self._value = float(value) def __repr__(self) -> str: return f"MyFloat({self._value})" def __float__(self) -> float: return self._value >>> supports_float(MyFloat(4)) 2.0 >>> only_float(MyFloat(4)) Traceback (most recent call last): File "", line 1, in TypeError: only_float(): incompatible function arguments. The following argument types are supported: 1. (f: float) -> float Invoked with: MyFloat(4) ``` -------------------------------- ### Create std::unique_ptr instance Source: https://pybind11.readthedocs.io/en/latest/advanced/smart_ptrs.html Example of a function returning a std::unique_ptr that can be bound to Python. ```cpp std::unique_ptr create_example() { return std::unique_ptr(new Example()); } ``` -------------------------------- ### Invoke functional bindings from Python Source: https://pybind11.readthedocs.io/en/latest/advanced/cast/functional.html Example usage of the bound C++ functions within a Python session. ```python $ python >>> import example >>> def square(i): ... return i * i ... >>> example.func_arg(square) 100L >>> square_plus_1 = example.func_ret(square) >>> square_plus_1(4) 17L >>> plus_1 = func_cpp() >>> plus_1(number=43) 44L ``` -------------------------------- ### Define Base and Derived Classes with Virtual Methods Source: https://pybind11.readthedocs.io/en/latest/advanced/classes.html Example of a base class with pure virtual and virtual methods, and a derived class that overrides them. ```cpp class Animal { public: virtual std::string go(int n_times) = 0; virtual std::string name() { return "unknown"; } }; class Dog : public Animal { public: std::string go(int n_times) override { std::string result; for (int i=0; i [VERSION ] [REQUIRED] [QUIET]) ``` -------------------------------- ### Import setup_helpers from a submodule Source: https://pybind11.readthedocs.io/en/latest/compiling.html Configures the Python path to import Pybind11Extension from a local submodule directory. ```python DIR = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(DIR, "extern", "pybind11")) from pybind11.setup_helpers import Pybind11Extension # noqa: E402 del sys.path[-1] ``` -------------------------------- ### Bind create_example function Source: https://pybind11.readthedocs.io/en/latest/advanced/smart_ptrs.html Binding the factory function to the module. ```cpp m.def("create_example", &create_example); ``` -------------------------------- ### Create Python Modules and Submodules Source: https://pybind11.readthedocs.io/en/latest/reference.html Demonstrates how to initialize a top-level module and define nested submodules using the py::module_ class. ```cpp py::module_ m("example", "pybind11 example plugin"); py::module_ m2 = m.def_submodule("sub", "A submodule of 'example'"); py::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'"); ``` -------------------------------- ### Initialize Eigen Matrix from Python buffer Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/numpy.html Demonstrates how to accept a Python buffer object in a C++ constructor and map it to an Eigen matrix. ```cpp /* Bind MatrixXd (or some other Eigen type) to Python */ typedef Eigen::MatrixXd Matrix; typedef Matrix::Scalar Scalar; constexpr bool rowMajor = Matrix::Flags & Eigen::RowMajorBit; py::class_(m, "Matrix", py::buffer_protocol()) .def(py::init([](py::buffer b) { typedef Eigen::Stride Strides; /* Request a buffer descriptor from Python */ py::buffer_info info = b.request(); /* Some basic validation checks ... */ if (!info.item_type_is_equivalent_to()) throw std::runtime_error("Incompatible format: expected a double array!"); if (info.ndim != 2) throw std::runtime_error("Incompatible buffer dimension!"); auto strides = Strides( info.strides[rowMajor ? 0 : 1] / (py::ssize_t)sizeof(Scalar), info.strides[rowMajor ? 1 : 0] / (py::ssize_t)sizeof(Scalar)); auto map = Eigen::Map( static_cast(info.ptr), info.shape[0], info.shape[1], strides); return Matrix(map); })); ``` -------------------------------- ### pybind11_find_import Source: https://pybind11.readthedocs.io/en/latest/cmake/index.html Checks if a Python module is installed. ```APIDOC ## pybind11_find_import ### Description See if a module is installed. Use the registered name (the one on PyPI). Only available if NOPYTHON mode is not active. Sets module_VERSION and module_FOUND. ### Signature `pybind11_find_import( [VERSION ] [REQUIRED] [QUIET])` ### Parameters - **module** - Required - The name of the module to find. - **VERSION** - Optional - Specify a version number. - **REQUIRED** - Optional - Fail if the module is not found. - **QUIET** - Optional - Suppress output. ``` -------------------------------- ### Compile and test on Windows Source: https://pybind11.readthedocs.io/en/latest/basics.html Use these commands to build and verify the library on Windows using Visual Studio. ```bash mkdir build cd build cmake .. cmake --build . --config Release --target check ``` -------------------------------- ### Define templated C++ classes Source: https://pybind11.readthedocs.io/en/latest/advanced/classes.html Example of C++ structures and a templated class to be wrapped. ```cpp struct Cat {}; struct Dog {}; template struct Cage { Cage(PetType& pet); PetType& get(); }; ``` -------------------------------- ### Invoke a vectorized function in Python Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/numpy.html Example usage of the vectorized function with NumPy arrays. ```python >>> x = np.array([[1, 3], [5, 7]]) >>> y = np.array([[2, 4], [6, 8]]) >>> z = 3 >>> result = vectorized_func(x, y, z) ``` -------------------------------- ### Enable parallel compilation in setuptools Source: https://pybind11.readthedocs.io/en/latest/compiling.html Uses the ParallelCompile helper to speed up builds by utilizing multiple threads. ```python from pybind11.setup_helpers import ParallelCompile # Optional multithreaded build ParallelCompile("NPY_NUM_BUILD_JOBS").install() setup(...) ``` -------------------------------- ### Import and use the module in Python Source: https://pybind11.readthedocs.io/en/latest/basics.html Interactive session demonstrating how to import the compiled module and call the bound function. ```python $ python Python 3.9.10 (main, Jan 15 2022, 11:48:04) [Clang 13.0.0 (clang-1300.0.29.3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import example >>> example.add(1, 2) 3 >>> ``` -------------------------------- ### C++ function with pass-by-reference vector Source: https://pybind11.readthedocs.io/en/latest/advanced/cast/stl.html Example of a C++ function that modifies a vector passed by reference. ```cpp void append_1(std::vector &v) { v.push_back(1); } ``` -------------------------------- ### Enable automatic C++ standard search in setuptools Source: https://pybind11.readthedocs.io/en/latest/compiling.html Overrides the build_ext command to automatically detect the highest supported C++ standard. ```python from glob import glob from setuptools import setup from pybind11.setup_helpers import Pybind11Extension, build_ext ext_modules = [ Pybind11Extension( "python_example", sorted(glob("src/*.cpp")), ), ] setup(..., cmdclass={"build_ext": build_ext}, ext_modules=ext_modules) ``` -------------------------------- ### Enable naive recompilation in setuptools Source: https://pybind11.readthedocs.io/en/latest/compiling.html Configures ParallelCompile to skip rebuilding files if the object file is newer than the source. ```python from pybind11.setup_helpers import ParallelCompile, naive_recompile ParallelCompile("NPY_NUM_BUILD_JOBS", needs_recompile=naive_recompile).install() ``` -------------------------------- ### Apply call_guard policy Source: https://pybind11.readthedocs.io/en/latest/reference.html Example of using py::call_guard to wrap a function call with a guard variable. ```cpp m.def("foo", foo, py::call_guard()); ``` ```cpp m.def("foo", [](args...) { T scope_guard; return foo(args...); // forwarded arguments }); ``` -------------------------------- ### Print object representation Source: https://pybind11.readthedocs.io/en/latest/classes.html Example output of printing a bound C++ object before custom representation is defined. ```python >>> print(p) ``` -------------------------------- ### Unpacking Python Arguments in C++ Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/object.html Demonstrates how to use py::tuple and py::dict to perform argument unpacking equivalent to Python's *args and **kwargs syntax. ```cpp // * unpacking py::tuple args = py::make_tuple(1234, "hello", some_instance); f(*args); // ** unpacking py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance); f(**kwargs); // mixed keywords, * and ** unpacking py::tuple args = py::make_tuple(1234); py::dict kwargs = py::dict("to"_a=some_instance); f(*args, "say"_a="hello", **kwargs); ``` -------------------------------- ### Instantiate a Python dictionary Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/object.html Initializes a dictionary using the dict constructor and keyword arguments. ```cpp using namespace pybind11::literals; // to bring in the `_a` literal py::dict d("spam"_a=py::none(), "eggs"_a=42); ``` -------------------------------- ### Invoking the bound dictionary function in Python Source: https://pybind11.readthedocs.io/en/latest/advanced/functions.html Example usage of the bound function within a Python environment. ```python >>> print_dict({"foo": 123, "bar": "hello"}) key=foo, value=123 key=bar, value=hello ``` -------------------------------- ### Verify None argument behavior in Python Source: https://pybind11.readthedocs.io/en/latest/advanced/functions.html Demonstrates the runtime behavior of functions configured with .none(true) and .none(false). ```python >>> from animals import Dog, Cat, bark, meow >>> bark(Dog()) 'woof!' >>> meow(Cat()) 'meow' >>> bark(None) '(no dog)' >>> meow(None) Traceback (most recent call last): File "", line 1, in TypeError: meow(): incompatible function arguments. The following argument types are supported: 1. (cat: animals.Cat) -> str Invoked with: None ``` -------------------------------- ### Example of a function type signature Source: https://pybind11.readthedocs.io/en/latest/faq.html The unmangled function type signature corresponding to the provided mangled symbol. ```cpp pybind11::cpp_function::cpp_function, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector, std::__1::allocator >, std::__1::allocator, std::__1::allocator > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28]) ``` -------------------------------- ### Using py::print in C++ Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/utilities.html Demonstrates how to use py::print to output data through Python's printing machinery, including support for keyword arguments like sep and end. ```cpp py::print(1, 2.0, "three"); // 1 2.0 three py::print(1, 2.0, "three", "sep"_a="-"); // 1-2.0-three auto args = py::make_tuple("unpacked", true); py::print("->", *args, "end"_a="<-"); // -> unpacked True <- ``` -------------------------------- ### Function accepting std::unique_ptr Source: https://pybind11.readthedocs.io/en/latest/advanced/smart_ptrs.html Example of a function signature that fails with standard std::unique_ptr holders. ```cpp void do_something_with_example(std::unique_ptr ex) { ... } ``` -------------------------------- ### Define a C++ class with nested types Source: https://pybind11.readthedocs.io/en/latest/advanced/deprecated.html Example C++ structure containing an enumeration and a nested struct. ```cpp struct Pet { enum Kind { Dog = 0, Cat }; struct Attributes { float age = 0; }; Pet(const std::string &name, Kind type) : name(name), type(type) { } std::string name; Kind type; Attributes attr; }; ``` -------------------------------- ### Define custom constructors Source: https://pybind11.readthedocs.io/en/latest/changelog.html Shows how to add custom constructors using lambdas or factory functions in py::class_. ```cpp struct Example { Example(std::string); }; py::class_(m, "Example") .def(py::init()) // existing constructor .def(py::init([](int n) { // custom constructor return std::make_unique(std::to_string(n)); })); ``` -------------------------------- ### Create and Activate Sub-interpreters in C++ Source: https://pybind11.readthedocs.io/en/latest/advanced/embedding.html Demonstrates defining an embedded module with per-interpreter GIL and managing sub-interpreter activation scopes. ```cpp #include #include #include namespace py = pybind11; PYBIND11_EMBEDDED_MODULE(printer, m, py::multiple_interpreters::per_interpreter_gil()) { m.def("which", [](const std::string& when) { std::cout << when << "; Current Interpreter is " << py::subinterpreter::current().id() << std::endl; }); } int main() { py::scoped_interpreter main_interp; py::module_::import("printer").attr("which")("First init"); { py::subinterpreter sub = py::subinterpreter::create(); py::module_::import("printer").attr("which")("Created sub"); { py::subinterpreter_scoped_activate guard(sub); try { py::module_::import("printer").attr("which")("Activated sub"); } catch (py::error_already_set &e) { std::cerr << "EXCEPTION " << e.what() << std::endl; return 1; } } py::module_::import("printer").attr("which")("Deactivated sub"); { py::gil_scoped_release nogil; { py::subinterpreter_scoped_activate guard(sub); try { { py::subinterpreter_scoped_activate main_guard(py::subinterpreter::main()); try { py::module_::import("printer").attr("which")("Main within sub"); } catch (py::error_already_set &e) { std::cerr << "EXCEPTION " << e.what() << std::endl; return 1; } } py::module_::import("printer").attr("which")("After Main, still within sub"); } catch (py::error_already_set &e) { std::cerr << "EXCEPTION " << e.what() << std::endl; return 1; } } } } py::module_::import("printer").attr("which")("At end"); return 0; } ``` -------------------------------- ### Compile using the --file helper Source: https://pybind11.readthedocs.io/en/latest/compiling.html Uses the --file argument to automatically generate the full compiler command for a specific source file. ```bash $ c++ $(python3 -m pybind11 --file=example.cpp) ``` -------------------------------- ### Print object representation after binding Source: https://pybind11.readthedocs.io/en/latest/classes.html Example output of printing a bound C++ object after defining a custom __repr__. ```python >>> print(p) ``` -------------------------------- ### Migrate custom constructors to py::init Source: https://pybind11.readthedocs.io/en/latest/upgrade.html Replace placement-new custom constructors with py::init() to improve type safety and prevent multiple initializations. ```cpp // old -- deprecated (runtime warning shown only in debug mode) py::class(m, "Foo") .def("__init__", [](Foo &self, ...) { new (&self) Foo(...); // uses placement-new }); // new py::class(m, "Foo") .def(py::init([](...) { // Note: no `self` argument return new Foo(...); // return by raw pointer // or: return std::make_unique(...); // return by holder // or: return Foo(...); // return by value (move constructor) })); ``` -------------------------------- ### Evaluating Python expressions and statements Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/utilities.html Demonstrates basic usage of eval, exec, and eval_file using a module scope. Requires including pybind11/eval.h. ```cpp // At beginning of file #include ... // Evaluate in scope of main module py::object scope = py::module_::import("__main__").attr("__dict__"); // Evaluate an isolated expression int result = py::eval("my_variable + 10", scope).cast(); // Evaluate a sequence of statements py::exec( "print('Hello')\n" "print('world!');", scope); // Evaluate the statements in an separate Python file on disk py::eval_file("script.py", scope); ``` -------------------------------- ### Customizing type setup Source: https://pybind11.readthedocs.io/en/latest/advanced/classes.html Manipulate PyHeapTypeObject directly to enable features like garbage collection for custom classes. ```cpp struct ContainerOwnsPythonObjects { std::vector list; void append(const py::object &obj) { list.emplace_back(obj); } py::object at(py::ssize_t index) const { if (index >= size() || index < 0) { throw py::index_error("Index out of range"); } return list.at(py::size_t(index)); } py::ssize_t size() const { return py::ssize_t_cast(list.size()); } void clear() { list.clear(); } }; py::class_ cls( m, "ContainerOwnsPythonObjects", py::custom_type_setup([](PyHeapTypeObject *heap_type) { auto *type = &heap_type->ht_type; type->tp_flags |= Py_TPFLAGS_HAVE_GC; type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) { // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse Py_VISIT(Py_TYPE(self_base)); if (py::detail::is_holder_constructed(self_base)) { auto &self = py::cast(py::handle(self_base)); for (auto &item : self.list) { Py_VISIT(item.ptr()); } } return 0; }; type->tp_clear = [](PyObject *self_base) { if (py::detail::is_holder_constructed(self_base)) { auto &self = py::cast(py::handle(self_base)); for (auto &item : self.list) { Py_CLEAR(item.ptr()); } self.list.clear(); } return 0; }; })); cls.def(py::init<>()); cls.def("append", &ContainerOwnsPythonObjects::append); cls.def("at", &ContainerOwnsPythonObjects::at); cls.def("size", &ContainerOwnsPythonObjects::size); cls.def("clear", &ContainerOwnsPythonObjects::clear); ``` -------------------------------- ### Construct a dictionary with keyword arguments Source: https://pybind11.readthedocs.io/en/latest/changelog.html Create a py::dict object using the _a literal for keyword arguments. ```cpp auto d = dict("number"_a=42, "name"_a="World"); ``` -------------------------------- ### pybind11Config.cmake Exported Variables Source: https://pybind11.readthedocs.io/en/latest/cmake/index.html Variables set by the pybind11 CMake module to provide information about the installation and required build flags. ```APIDOC ## pybind11Config.cmake Exported Variables ### Description The following variables are set in your project upon successfully finding pybind11: - **pybind11_FOUND** (bool): True if pybind11 and all required components are found. - **pybind11_VERSION** (string): The pybind11 version in Major.Minor.Release format. - **pybind11_VERSION_TYPE** (string): The version type (e.g., 'dev*' or empty for release). - **pybind11_INCLUDE_DIRS** (list): Directories containing pybind11 and Python headers. - **pybind11_INCLUDE_DIR** (string): Directory containing pybind11 headers. - **pybind11_DEFINITIONS** (list): Definitions required to use pybind11 (e.g., USING_pybind11). - **pybind11_LIBRARIES** (list): Compile flags and Python libraries required for linking. ``` -------------------------------- ### Build a complex module using interface targets Source: https://pybind11.readthedocs.io/en/latest/compiling.html Demonstrates how to use pybind11 interface targets like pybind11::module, pybind11::lto, and pybind11::windows_extras to configure a module build. ```cmake cmake_minimum_required(VERSION 3.15...4.2) project(example LANGUAGES CXX) find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11) add_library(example MODULE main.cpp) target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras) pybind11_extension(example) if(NOT MSVC AND NOT ${CMAKE_BUILD_TYPE} MATCHES Debug|RelWithDebInfo) # Strip unnecessary sections of the binary on Linux/macOS pybind11_strip(example) endif() set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden" CUDA_VISIBILITY_PRESET "hidden") ``` -------------------------------- ### Compile the module on Linux Source: https://pybind11.readthedocs.io/en/latest/basics.html Command-line instruction for compiling the C++ source into a Python-importable binary module. ```bash $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3 -m pybind11 --extension-suffix) ``` -------------------------------- ### Advanced Factory Function Bindings Source: https://pybind11.readthedocs.io/en/latest/advanced/classes.html Demonstrates mixing factory functions returning raw pointers or smart pointers with standard C++ constructor bindings. ```cpp class Example { private: Example(int); // private constructor public: // Factory function - returned by value: static Example create(int a) { return Example(a); } // These constructors are publicly callable: Example(double); Example(int, int); Example(std::string); }; py::class_(m, "Example") // Bind the factory function as a constructor: .def(py::init(&Example::create)) // Bind a lambda function returning a pointer wrapped in a holder: .def(py::init([](std::string arg) { return std::unique_ptr(new Example(arg)); })) // Return a raw pointer: .def(py::init([](int a, int b) { return new Example(a, b); })) // You can mix the above with regular C++ constructor bindings as well: .def(py::init()) ; ``` -------------------------------- ### Define pybind11 class bindings Source: https://pybind11.readthedocs.io/en/latest/benchmark.html Example of binding a C++ class with multiple methods to a Python module using pybind11. ```cpp ... class cl034 { public: cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *); cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *); cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *); cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *); }; ... PYBIND11_MODULE(example, m, py::mod_gil_not_used()) { ... py::class_(m, "cl034") .def("fn_000", &cl034::fn_000) .def("fn_001", &cl034::fn_001) .def("fn_002", &cl034::fn_002) .def("fn_003", &cl034::fn_003) ... } ``` -------------------------------- ### Compile using pybind11 flag helpers Source: https://pybind11.readthedocs.io/en/latest/compiling.html Uses pybind11's built-in flag generation to simplify compiler arguments. ```bash $ c++ $(python3 -m pybind11 --cflags) example.cpp $(python3 -m pybind11 --ldflags) -o example$(python3 -m pybind11 --extension-suffix) ``` -------------------------------- ### Manual buffer access for array operations Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/numpy.html Example of manually accessing and processing NumPy array buffers in C++ when vectorization is insufficient. ```cpp #include #include namespace py = pybind11; py::array_t add_arrays(py::array_t input1, py::array_t input2) { py::buffer_info buf1 = input1.request(), buf2 = input2.request(); if (buf1.ndim != 1 || buf2.ndim != 1) throw std::runtime_error("Number of dimensions must be one"); if (buf1.size != buf2.size) throw std::runtime_error("Input shapes must match"); /* No pointer is passed, so NumPy will allocate the buffer */ auto result = py::array_t(buf1.size); py::buffer_info buf3 = result.request(); double *ptr1 = static_cast(buf1.ptr); double *ptr2 = static_cast(buf2.ptr); double *ptr3 = static_cast(buf3.ptr); for (size_t idx = 0; idx < buf1.shape[0]; idx++) ptr3[idx] = ptr1[idx] + ptr2[idx]; return result; } PYBIND11_MODULE(test, m, py::mod_gil_not_used()) { m.def("add_arrays", &add_arrays, "Add two NumPy arrays"); } ``` -------------------------------- ### Apply return value policy to class properties Source: https://pybind11.readthedocs.io/en/latest/advanced/functions.html Demonstrates applying a return value policy to a property getter and setter using the terse syntax. ```cpp class_(m, "MyClass") .def_property("data", &MyClass::getData, &MyClass::setData, py::return_value_policy::copy); ``` -------------------------------- ### Replace py::make_simple_namespace Source: https://pybind11.readthedocs.io/en/latest/upgrade.html Use the module import approach for SimpleNamespace instead of the deprecated helper function. ```cpp py::module_::import("types").attr("SimpleNamespace") ``` -------------------------------- ### Exposing C++ Buffers as Memoryview Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/numpy.html Shows how to create a 2D memoryview from a C++ buffer. The user must ensure the buffer lifetime exceeds the memoryview usage. ```cpp const uint8_t buffer[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; m.def("get_memoryview2d", []() { return py::memoryview::from_buffer( buffer, // buffer pointer { 2, 4 }, // shape (rows, cols) { sizeof(uint8_t) * 4, sizeof(uint8_t) } // strides in bytes ); }); ``` -------------------------------- ### Macro argument comma limitation Source: https://pybind11.readthedocs.io/en/latest/advanced/misc.html Example of a macro call that fails due to commas in template arguments being interpreted as argument separators by the preprocessor. ```cpp PYBIND11_OVERRIDE(MyReturnType, Class, func) ``` -------------------------------- ### Configure Meson build for pybind11 Source: https://pybind11.readthedocs.io/en/latest/compiling.html Defines the project structure and dependencies for a Meson-based build. ```meson project( 'example', 'cpp', version: '0.1.0', default_options: [ 'cpp_std=c++11', ], ) py = import('python').find_installation(pure: false) pybind11_dep = dependency('pybind11') py.extension_module('example', 'example.cpp', install: true, dependencies : [pybind11_dep], ) ``` -------------------------------- ### Configure a Python extension module with CMake Source: https://pybind11.readthedocs.io/en/latest/compiling.html Use this CMake configuration to define a project and add a pybind11 module. Ensure pybind11 is installed and discoverable via find_package. ```cmake cmake_minimum_required(VERSION 3.15...4.2) project(example LANGUAGES CXX) set(PYBIND11_FINDPYTHON ON) find_package(pybind11 CONFIG REQUIRED) pybind11_add_module(example example.cpp) install(TARGETS example DESTINATION .) ``` -------------------------------- ### Define C++ functions for callback binding Source: https://pybind11.readthedocs.io/en/latest/advanced/cast/functional.html Examples of C++ functions that accept or return std::function objects, and a function using py::cpp_function for named arguments. ```cpp int func_arg(const std::function &f) { return f(10); } ``` ```cpp std::function func_ret(const std::function &f) { return [f](int i) { return f(i) + 1; }; } ``` ```cpp py::cpp_function func_cpp() { return py::cpp_function([](int i) { return i+1; }, py::arg("number")); } ``` -------------------------------- ### Define a Python module with PYBIND11_MODULE Source: https://pybind11.readthedocs.io/en/latest/reference.html Use this macro to create the entry point for a Python extension module. The first argument is the module name, and the second is the variable name for the module object. ```cpp PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example module"; // Add bindings here m.def("foo", []() { return "Hello, World!"; }); } ``` ```cpp PYBIND11_MODULE(example, m, py::mod_gil_not_used()) { m.doc() = "pybind11 example module safe to run without the GIL"; m.def("foo", []() { return "Hello, Free-threaded World!"; }); } ``` -------------------------------- ### Binding C++ classes with raw pointer return issues Source: https://pybind11.readthedocs.io/en/latest/classes.html Example demonstrating a C++ class returning a raw pointer to a shared_ptr member, which causes ownership conflicts when bound in pybind11. ```cpp class Child { }; class Parent { public: Parent() : child(std::make_shared()) { } Child *get_child() { return child.get(); } /* DANGER */ private: std::shared_ptr child; }; PYBIND11_MODULE(example, m, py::mod_gil_not_used()) { py::class_>(m, "Child"); py::class_>(m, "Parent") .def(py::init<>()) .def("get_child", &Parent::get_child); /* PROBLEM */ } ``` -------------------------------- ### Include pybind11 headers and namespace Source: https://pybind11.readthedocs.io/en/latest/basics.html Standard boilerplate for pybind11 source files. Must be included before other headers due to Python.h requirements. ```cpp #include namespace py = pybind11; ``` -------------------------------- ### Pickle an Instance in Python Source: https://pybind11.readthedocs.io/en/latest/advanced/classes.html Demonstrates how to use the standard Python pickle module to serialize an instance of the bound C++ class. ```python import pickle p = Pickleable("test_value") p.setExtra(15) data = pickle.dumps(p) ``` -------------------------------- ### Implement custom method signatures with get_override Source: https://pybind11.readthedocs.io/en/latest/advanced/classes.html Use get_override to manually handle Python method calls from C++ when direct mapping is not possible. This example demonstrates converting Python return types to C++ reference arguments. ```cpp bool MyClass::myMethod(int32_t& value) { pybind11::gil_scoped_acquire gil; // Acquire the GIL while in this scope. // Try to look up the overridden method on the Python side. pybind11::function override = pybind11::get_override(this, "myMethod"); if (override) { // method is found auto obj = override(value); // Call the Python function. if (py::isinstance(obj)) { // check if it returned a Python integer type value = obj.cast(); // Cast it and assign it to the value. return true; // Return true; value should be used. } else { return false; // Python returned none, return false. } } return false; // Alternatively return MyClass::myMethod(value); } ``` -------------------------------- ### Interact with bound C++ class in Python Source: https://pybind11.readthedocs.io/en/latest/classes.html Demonstration of instantiating and using the bound Pet class within a Python session. ```python % python >>> import example >>> p = example.Pet("Molly") >>> print(p) >>> p.getName() 'Molly' >>> p.setName("Charly") >>> p.getName() 'Charly' ``` -------------------------------- ### initialize_interpreter Source: https://pybind11.readthedocs.io/en/latest/reference.html Initializes the Python interpreter. ```APIDOC ## void initialize_interpreter(PyConfig *config, int argc = 0, const char *const *argv = nullptr, bool add_program_dir_to_path = true) ## void initialize_interpreter(bool init_signal_handlers = true, int argc = 0, const char *const *argv = nullptr, bool add_program_dir_to_path = true) ### Description Initializes the Python interpreter. Must be called before using pybind11 objects. ``` -------------------------------- ### View overloaded method signatures in Python Source: https://pybind11.readthedocs.io/en/latest/classes.html The help function displays the generated overload signatures in the docstring. ```python >>> help(example.Pet) class Pet(__builtin__.object) | Methods defined here: | | __init__(...) | Signature : (Pet, str, int) -> NoneType | | set(...) | 1. Signature : (Pet, int) -> NoneType | | Set the pet's age | | 2. Signature : (Pet, str) -> NoneType | | Set the pet's name ``` -------------------------------- ### Instantiate a SimpleNamespace Source: https://pybind11.readthedocs.io/en/latest/advanced/pycpp/object.html Creates a SimpleNamespace object by importing it from the types module. ```cpp using namespace pybind11::literals; // to bring in the `_a` literal py::object SimpleNamespace = py::module_::import("types").attr("SimpleNamespace"); py::object ns = SimpleNamespace("spam"_a=py::none(), "eggs"_a=42); ``` -------------------------------- ### Initial pybind11 Module Binding Source: https://pybind11.readthedocs.io/en/latest/advanced/classes.html Basic binding code that does not yet support Python-side overrides. ```cpp PYBIND11_MODULE(example, m, py::mod_gil_not_used()) { py::class_(m, "Animal") .def("go", &Animal::go); py::class_(m, "Dog") .def(py::init<>()); m.def("call_go", &call_go); } ``` -------------------------------- ### Accept module-local types as function arguments Source: https://pybind11.readthedocs.io/en/latest/advanced/classes.html Demonstrates that module-local types remain compatible when passed as arguments to C++ functions. ```cpp m.def("pet_name", [](const pets::Pet &pet) { return pet.name(); }); ``` ```python >>> import cats, dogs, frogs # No error because of the added py::module_local() >>> mycat, mydog = cats.Cat("Fluffy"), dogs.Dog("Rover") >>> (cats.pet_name(mycat), dogs.pet_name(mydog)) ('Fluffy', 'Rover') >>> (cats.pet_name(mydog), dogs.pet_name(mycat), frogs.pet_name(mycat)) ('Rover', 'Fluffy', 'Fluffy') ``` -------------------------------- ### Migrate module entry points from PYBIND11_PLUGIN to PYBIND11_MODULE Source: https://pybind11.readthedocs.io/en/latest/upgrade.html Use the PYBIND11_MODULE macro to define module entry points, as the older PYBIND11_PLUGIN macro is deprecated. ```cpp // old PYBIND11_PLUGIN(example) { py::module m("example", "documentation string"); m.def("add", [](int a, int b) { return a + b; }); return m.ptr(); } // new PYBIND11_MODULE(example, m) { m.doc() = "documentation string"; // optional m.def("add", [](int a, int b) { return a + b; }); } ``` -------------------------------- ### Binding Eigen matrices with return value policies Source: https://pybind11.readthedocs.io/en/latest/advanced/cast/eigen.html Demonstrates how to bind C++ methods returning Eigen matrices to Python, using reference_internal to manage object lifetimes and avoid unnecessary copies. ```cpp class MyClass { Eigen::MatrixXd big_mat = Eigen::MatrixXd::Zero(10000, 10000); public: Eigen::MatrixXd &getMatrix() { return big_mat; } const Eigen::MatrixXd &viewMatrix() { return big_mat; } }; // Later, in binding code: py::class_(m, "MyClass") .def(py::init<>()) .def("copy_matrix", &MyClass::getMatrix) // Makes a copy! .def("get_matrix", &MyClass::getMatrix, py::return_value_policy::reference_internal) .def("view_matrix", &MyClass::viewMatrix, py::return_value_policy::reference_internal) ; ``` -------------------------------- ### Configure pyproject.toml for build requirements Source: https://pybind11.readthedocs.io/en/latest/compiling.html Defines the build system requirements and backend for projects using pybind11. ```toml [build-system] requires = ["setuptools", "pybind11"] build-backend = "setuptools.build_meta" ``` -------------------------------- ### Interfacing with Windows API using std::wstring Source: https://pybind11.readthedocs.io/en/latest/advanced/cast/strings.html Demonstrates passing and returning wide strings for Windows API calls, where pybind11 handles the encoding conversion. ```cpp #define UNICODE #include m.def("set_window_text", [](HWND hwnd, std::wstring s) { // Call SetWindowText with null-terminated UTF-16 string ::SetWindowText(hwnd, s.c_str()); } ); m.def("get_window_text", [](HWND hwnd) { const int buffer_size = ::GetWindowTextLength(hwnd) + 1; auto buffer = std::make_unique< wchar_t[] >(buffer_size); ::GetWindowText(hwnd, buffer.data(), buffer_size); std::wstring text(buffer.get()); // wstring will be converted to Python str return text; } ); ```