PyBindGen

0.22.1 · active · verified Fri Apr 17

PyBindGen is a code generator that produces C++ source files to create Python bindings for C/C++ libraries. It helps expose C/C++ functions and classes to Python without writing manual wrapper code. As of version 0.22.1, it's an active project with a slow but steady release cadence, often tied to changes in `ns-3` (its primary consumer).

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple Python module that wraps a C++ function `add(int, int)`. The `generate_bindings` function creates a `Module` instance, adds a function definition with its parameters and return value, and then generates the C++ source file `my_bindings_module.cc`. This generated file then needs to be compiled into a Python extension module using a C++ compiler and a build system like `setuptools` or `waf`.

from pybindgen import Module, Function, Parameter, ReturnValue

def generate_bindings(filename):
    module = Module('my_bindings_module', cpp_namespace='MyCppNamespace')

    # Example: Bind a simple C++ function 'int add(int a, int b);'
    module.add_function(
        'add',
        retval=ReturnValue.copy(Parameter.new('int', 'a')),
        params=[Parameter.new('int', 'a'), Parameter.new('int', 'b')]
    )

    # Generate the C++ binding code
    module.generate(filename)
    print(f"Generated binding code to {filename}")

# To run this, you would typically integrate it into a setup.py or build script
# For a standalone example:
# generate_bindings('my_bindings_module.cc')

view raw JSON →