cppclass: wrap C++ classes or C structures

class pybindgen.cppclass.BoostSharedPtr(class_name)

Bases: pybindgen.cppclass.SmartPointerPolicy

Create a memory policy for using boost::shared_ptr<> to manage instances of this object.

Parameters:class_name – the full name of the class, e.g. foo::Bar
get_delete_code(cpp_class)
get_instance_creation_function()
get_pointer_type(class_full_name)
get_pystruct_init_code(cpp_class, obj)
class pybindgen.cppclass.CppClass(name, parent=None, incref_method=None, decref_method=None, automatic_type_narrowing=None, allow_subclassing=None, is_singleton=False, outer_class=None, peekref_method=None, template_parameters=(), custom_template_class_name=None, incomplete_type=False, free_function=None, incref_function=None, decref_function=None, python_name=None, memory_policy=None, foreign_cpp_namespace=None, docstring=None, custom_name=None, import_from_module=None, destructor_visibility='public')

Bases: object

A CppClass object takes care of generating the code for wrapping a C++ class

Parameters:
  • name – class name
  • parent – optional parent class wrapper, or list of parents. Valid values are None, a CppClass instance, or a list of CppClass instances.
  • incref_method – (deprecated in favour of memory_policy) if the class supports reference counting, the name of the method that increments the reference count (may be inherited from parent if not given)
  • decref_method – (deprecated in favour of memory_policy) if the class supports reference counting, the name of the method that decrements the reference count (may be inherited from parent if not given)
  • automatic_type_narrowing – if True, automatic return type narrowing will be done on objects of this class and its descendants when returned by pointer from a function or method.
  • allow_subclassing – if True, generated class wrappers will allow subclassing in Python.
  • is_singleton – if True, the class is considered a singleton, and so the python wrapper will never call the C++ class destructor to free the value.
  • peekref_method – (deprecated in favour of memory_policy) if the class supports reference counting, the name of the method that returns the current reference count.
  • free_function – (deprecated in favour of memory_policy) name of C function used to deallocate class instances
  • incref_function – (deprecated in favour of memory_policy) same as incref_method, but as a function instead of method
  • decref_function – (deprecated in favour of memory_policy) same as decref_method, but as a function instead of method
  • python_name – name of the class as it will appear from Python side. This parameter is DEPRECATED in favour of custom_name.
  • memory_policy (L{MemoryPolicy}) – memory management policy; if None, it inherits from the parent class. Only root classes can have a memory policy defined.
  • foreign_cpp_namespace – if set, the class is assumed to belong to the given C++ namespace, regardless of the C++ namespace of the python module it will be added to. For instance, this can be useful to wrap std classes, like std::ofstream, without having to create an extra python submodule.
  • docstring – None or a string containing the docstring that will be generated for the class
  • custom_name – an alternative name to give to this class at python-side; if omitted, the name of the class in the python module will be the same name as the class in C++ (minus namespace).
  • import_from_module – if not None, the type is imported from a foreign Python module with the given name.
add_binary_comparison_operator(operator)

Add support for a C++ binary comparison operator, such as == or <.

The binary operator is assumed to operate with both operands of the type of the class, either by reference or by value.

Parameters:operator – string indicating the name of the operator to support, e.g. ‘==’
add_binary_numeric_operator(operator, result_cppclass=None, left_cppclass=None, right=None)

Add support for a C++ binary numeric operator, such as +, -, *, or /.

Parameters:
  • operator – string indicating the name of the operator to support, e.g. ‘==’
  • result_cppclass – the CppClass object of the result type, assumed to be this class if omitted
  • left_cppclass – the CppClass object of the left operand type, assumed to be this class if omitted
  • right – the type of the right parameter. Can be a CppClass, Parameter, or param spec. Assumed to be this class if omitted
add_class(*args, **kwargs)

Add a nested class. See L{CppClass} for information about accepted parameters.

add_constructor(*args, **kwargs)

Add a constructor to the class. See the documentation for L{CppConstructor.__init__} for information on accepted parameters.

add_container_traits(*args, **kwargs)
add_copy_constructor()

Utility method to add a ‘copy constructor’ method to this class.

add_custom_instance_attribute(name, value_type, getter, is_const=False, setter=None, getter_template_parameters=[], setter_template_parameters=[])
Parameters:
  • value_type – a ReturnValue object
  • name – attribute name (i.e. the name of the class member variable)
  • is_const – True if the attribute is const, i.e. cannot be modified
  • getter – None, or name of a method of this class used to get the value
  • setter – None, or name of a method of this class used to set the value
  • getter_template_parameters – optional list of template parameters for getter function
  • setter_template_parameters – optional list of template parameters for setter function
add_custom_method_wrapper(*args, **kwargs)

Adds a custom method wrapper. See L{CustomCppMethodWrapper} for more information.

add_enum(*args, **kwargs)

Add a nested enum. See L{Enum} for information about accepted parameters.

add_function_as_constructor(*args, **kwargs)

Wrap a function that behaves as a constructor to the class. See the documentation for L{CppFunctionAsConstructor.__init__} for information on accepted parameters.

add_function_as_method(*args, **kwargs)

Add a function as method of the class. See the documentation for L{Function.__init__} for information on accepted parameters. TODO: explain the implicit first function parameter

add_helper_class_hook(hook)

Add a hook function to be called just prior to a helper class being generated. The hook function applies to this class and all subclasses. The hook function is called like this:

hook_function(helper_class)
add_inplace_numeric_operator(operator, right=None)

Add support for a C++ inplace numeric operator, such as +=, -=, *=, or /=.

Parameters:
  • operator – string indicating the name of the operator to support, e.g. ‘+=’
  • right – the type of the right parameter. Can be a CppClass, Parameter, or param spec. Assumed to be this class if omitted
add_instance_attribute(name, value_type, is_const=False, getter=None, setter=None)
Parameters:
  • value_type – a ReturnValue object
  • name – attribute name (i.e. the name of the class member variable)
  • is_const – True if the attribute is const, i.e. cannot be modified
  • getter – None, or name of a method of this class used to get the value
  • setter – None, or name of a method of this class used to set the value
add_method(*args, **kwargs)

Add a method to the class. See the documentation for L{CppMethod.__init__} for information on accepted parameters.

add_output_stream_operator()

Add str() support based on C++ output stream operator.

Calling this method enables wrapping of an assumed to be defined operator function:

std::ostream & operator << (std::ostream &, MyClass const &);

The wrapper will be registered as an str() python operator, and will call the C++ operator function to convert the value to a string.

add_static_attribute(name, value_type, is_const=False)
Parameters:
  • value_type – a ReturnValue object
  • name – attribute name (i.e. the name of the class member variable)
  • is_const – True if the attribute is const, i.e. cannot be modified
add_unary_numeric_operator(operator, result_cppclass=None, left_cppclass=None)

Add support for a C++ unary numeric operators, currently only -.

Parameters:
  • operator – string indicating the name of the operator to support, e.g. ‘-‘
  • result_cppclass – the CppClass object of the result type, assumed to be this class if omitted
  • left_cppclass – the CppClass object of the left operand type, assumed to be this class if omitted
generate(code_sink, module)

Generates the class to a code sink

generate_forward_declarations(code_sink, module)

Generates forward declarations for the instance and type structures.

generate_typedef(module, alias)

Generates the appropriate Module code to register the class with a new name in that module (typedef alias).

get_all_implicit_conversions()

Gets a new list of all other classes whose value can be implicitly converted to a value of this class.

>>> Foo = CppClass("Foo")
>>> Bar = CppClass("Bar")
>>> Zbr = CppClass("Zbr")
>>> Bar.implicitly_converts_to(Foo)
>>> Zbr.implicitly_converts_to(Bar)
>>> l = Foo.get_all_implicit_conversions()
>>> l.sort(lambda cls1, cls2: cmp(cls1.name, cls2.name))
>>> [cls.name for cls in l]
['Bar']
get_all_methods()

Returns an iterator to iterate over all methods of the class

get_construct_name()

Get a name usable for new %s construction, or raise CodeGenerationError if none found

get_have_pure_virtual_methods()

Returns True if the class has pure virtual methods with no implementation (which would mean the type is not instantiable directly, only through a helper class).

get_helper_class()

gets the “helper class” for this class wrapper, creating it if necessary

get_instance_creation_function()
get_module()

Get the Module object this class belongs to

get_mro()

Get the method resolution order (MRO) of this class.

Returns:an iterator that gives CppClass objects, from leaf to root class
get_post_instance_creation_function()
get_pystruct()
get_python_name()
get_type_narrowing_root()

Find the root CppClass along the subtree of all parent classes that have automatic_type_narrowing=True Note: multiple inheritance not implemented

have_pure_virtual_methods

Returns True if the class has pure virtual methods with no implementation (which would mean the type is not instantiable directly, only through a helper class).

have_sequence_methods()

Determine if this object has sequence methods registered.

implicitly_converts_to(other)

Declares that values of this class can be implicitly converted to another class; corresponds to a operator AnotherClass(); special method.

inherit_default_constructors()

inherit the default constructors from the parentclass according to C++ language rules

is_subclass(other)

Return True if this CppClass instance represents a class that is a subclass of another class represented by the CppClasss object `other’.

module

Get the Module object this class belongs to

pystruct
register_alias(alias)

Re-register the class with another base name, in addition to any registrations that might have already been done.

set_cannot_be_constructed(reason)
set_helper_class_disabled(flag=True)
set_instance_creation_function(instance_creation_function)

Set a custom function to be called to create instances of this class and its subclasses.

Parameters:instance_creation_function – instance creation function; see default_instance_creation_function() for signature and example.
set_module(module)

Set the Module object this class belongs to

set_post_instance_creation_function(post_instance_creation_function)

Set a custom function to be called to add code after an instance is created (usually by the “instance creation function”) and registered with the Python runtime.

Parameters:post_instance_creation_function – post instance creation function
wrapper_registry
write_allocate_pystruct(code_block, lvalue, wrapper_type=None)

Generates code to allocate a python wrapper structure, using PyObject_New or PyObject_GC_New, plus some additional strcture initialization that may be needed.

write_create_instance(code_block, lvalue, parameters, construct_type_name=None)
write_post_instance_creation_code(code_block, lvalue, parameters, construct_type_name=None)
class pybindgen.cppclass.CppClassParameter(ctype, name, direction=1, is_const=False, default_value=None)

Bases: pybindgen.cppclass.CppClassParameterBase

Class parameter “by-value” handler

Parameters:
  • ctype – C type, normally ‘MyClass*’
  • name – parameter name
CTYPES = []
DIRECTIONS = [1]
convert_c_to_python(wrapper)

Write some code before calling the Python method.

convert_python_to_c(wrapper)

parses python args to get C++ value

cpp_class = None
class pybindgen.cppclass.CppClassParameterBase(ctype, name, direction=1, is_const=False, default_value=None)

Bases: pybindgen.typehandlers.base.Parameter

Base class for all C++ Class parameter handlers

Parameters:
  • ctype – C type, normally ‘MyClass*’
  • name – parameter name
CTYPES = []
DIRECTIONS = [1]
cpp_class = None
class pybindgen.cppclass.CppClassPtrParameter(ctype, name, direction=1, transfer_ownership=None, custodian=None, is_const=False, null_ok=False, default_value=None)

Bases: pybindgen.cppclass.CppClassParameterBase

Class* handlers

Type handler for a pointer-to-class parameter (MyClass*)

Parameters:
  • ctype – C type, normally ‘MyClass*’
  • name – parameter name
  • transfer_ownership – if True, the callee becomes responsible for freeing the object. If False, the caller remains responsible for the object. In either case, the original object pointer is passed, not a copy. In case transfer_ownership=True, it is invalid to perform operations on the object after the call (calling any method will cause a null pointer dereference and crash the program).
  • custodian

    if given, points to an object (custodian) that keeps the python wrapper for the parameter alive. Possible values are:

    • None: no object is custodian;
    • -1: the return value object;
    • 0: the instance of the method in which
      the ReturnValue is being used will become the custodian;
    • integer > 0: parameter number, starting at 1
      (i.e. not counting the self/this parameter), whose object will be used as custodian.
  • is_const – if true, the parameter has a const attached to the leftmost
  • null_ok – if true, None is accepted and mapped into a C NULL pointer
  • default_value – default parameter value (as C expression string); probably, the only default value that makes sense here is probably ‘NULL’.

Note

Only arguments which are instances of C++ classes wrapped by PyBindGen can be used as custodians.

CTYPES = []
DIRECTIONS = [1, 2, 3]
SUPPORTS_TRANSFORMATIONS = True
convert_c_to_python(wrapper)

foo

convert_python_to_c(wrapper)

parses python args to get C++ value

cpp_class = None
class pybindgen.cppclass.CppClassPtrReturnValue(ctype, caller_owns_return=None, custodian=None, is_const=False, reference_existing_object=None, return_internal_reference=None)

Bases: pybindgen.cppclass.CppClassReturnValueBase

Class* return handler

Parameters:
  • ctype – C type, normally ‘MyClass*’
  • caller_owns_return – if true, ownership of the object pointer is transferred to the caller
  • custodian

    bind the life cycle of the python wrapper for the return value object (ward) to that of the object indicated by this parameter (custodian). Possible values are:

    • None: no object is custodian;
    • 0: the instance of the method in which
      the ReturnValue is being used will become the custodian;
    • integer > 0: parameter number, starting at 1
      (i.e. not counting the self/this parameter), whose object will be used as custodian.
  • reference_existing_object – if true, ownership of the pointed-to object remains to be the caller’s, but we do not make a copy. The callee gets a reference to the existing object, but is not responsible for freeing it. Note that using this memory management style is dangerous, as it exposes the Python programmer to the possibility of keeping a reference to an object that may have been deallocated in the mean time. Calling methods on such an object would lead to a memory error.
  • return_internal_reference – like reference_existing_object, but additionally adds custodian/ward to bind the lifetime of the ‘self’ object (instance the method is bound to) to the lifetime of the return value.

Note

Only arguments which are instances of C++ classes wrapped by PyBindGen can be used as custodians.

CTYPES = []
SUPPORTS_TRANSFORMATIONS = True
convert_c_to_python(wrapper)

See ReturnValue.convert_c_to_python

convert_python_to_c(wrapper)

See ReturnValue.convert_python_to_c

cpp_class = None
get_c_error_return()

See ReturnValue.get_c_error_return

class pybindgen.cppclass.CppClassRefParameter(ctype, name, direction=1, is_const=False, default_value=None, default_value_type=None)

Bases: pybindgen.cppclass.CppClassParameterBase

Class& handlers

Parameters:
  • ctype – C type, normally ‘MyClass*’
  • name – parameter name
CTYPES = []
DIRECTIONS = [1, 2, 3]
convert_c_to_python(wrapper)

Write some code before calling the Python method.

convert_python_to_c(wrapper)

parses python args to get C++ value

cpp_class = None
class pybindgen.cppclass.CppClassRefReturnValue(ctype, is_const=False, caller_owns_return=False, reference_existing_object=None, return_internal_reference=None)

Bases: pybindgen.cppclass.CppClassReturnValueBase

Class return handlers

CTYPES = []
REQUIRES_ASSIGNMENT_CONSTRUCTOR = True
convert_c_to_python(wrapper)

see ReturnValue.convert_c_to_python

convert_python_to_c(wrapper)

see ReturnValue.convert_python_to_c

cpp_class = None
get_c_error_return()

See ReturnValue.get_c_error_return

class pybindgen.cppclass.CppClassReturnValue(ctype, is_const=False)

Bases: pybindgen.cppclass.CppClassReturnValueBase

Class return handlers

override to fix the ctype parameter with namespace information

CTYPES = []
REQUIRES_ASSIGNMENT_CONSTRUCTOR = True
convert_c_to_python(wrapper)

see ReturnValue.convert_c_to_python

convert_python_to_c(wrapper)

see ReturnValue.convert_python_to_c

cpp_class = None
get_c_error_return()

See ReturnValue.get_c_error_return

class pybindgen.cppclass.CppClassReturnValueBase(ctype, is_const=False)

Bases: pybindgen.typehandlers.base.ReturnValue

Class return handlers – base class

CTYPES = []
cpp_class = None
class pybindgen.cppclass.CppClassSharedPtrParameter(ctype, name, direction=1, is_const=False, null_ok=False, default_value=None)

Bases: pybindgen.cppclass.CppClassParameterBase

Class* handlers

Type handler for a pointer-to-class parameter (MyClass*)

Parameters:
  • ctype – C type, normally ‘MyClass*’
  • name – parameter name
  • is_const – if true, the parameter has a const attached to the leftmost
  • null_ok – if true, None is accepted and mapped into a C NULL pointer
  • default_value – default parameter value (as C expression string); probably, the only default value that makes sense here is probably ‘NULL’.

Note

Only arguments which are instances of C++ classes wrapped by PyBindGen can be used as custodians.

CTYPES = []
DIRECTIONS = [1, 2, 3]
SUPPORTS_TRANSFORMATIONS = False
convert_c_to_python(wrapper)

foo

convert_python_to_c(wrapper)

parses python args to get C++ value

cpp_class = None
class pybindgen.cppclass.CppClassSharedPtrReturnValue(ctype, is_const=False)

Bases: pybindgen.cppclass.CppClassReturnValueBase

Class* return handler

Parameters:ctype – C type, normally ‘MyClass*’
CTYPES = []
SUPPORTS_TRANSFORMATIONS = True
convert_c_to_python(wrapper)

See ReturnValue.convert_c_to_python

convert_python_to_c(wrapper)

See ReturnValue.convert_python_to_c

cpp_class = None
get_c_error_return()

See ReturnValue.get_c_error_return

class pybindgen.cppclass.CppHelperClass(class_)

Bases: object

Generates code for a C++ proxy subclass that takes care of forwarding virtual methods from C++ to Python.

Parameters:class – original CppClass wrapper object
add_custom_method(declaration, body=None)

Add a custom method to the helper class, given by a declaration line and a body. The body can be None, in case the whole method definition is included in the declaration itself.

add_post_generation_code(code)

Add custom code to be included right after the helper class is generated.

add_virtual_method(method)
add_virtual_parent_caller(parent_caller)

Add a new CppVirtualMethodParentCaller object to this helper class

add_virtual_proxy(virtual_proxy)

Add a new CppVirtualMethodProxy object to this class

generate(code_sink)

Generate the proxy class (virtual method bodies only) to a given code sink. returns pymethodef list of parent callers

generate_forward_declarations(code_sink_param)

Generate the proxy class (declaration only) to a given code sink

class pybindgen.cppclass.FreeFunctionPolicy(free_function)

Bases: pybindgen.cppclass.MemoryPolicy

get_delete_code(cpp_class)
class pybindgen.cppclass.MemoryPolicy

Bases: object

memory management policy for a C++ class or C/C++ struct

get_delete_code(cpp_class)
get_free_code(object_expression)

Return a code statement to free an underlying C/C++ object.

get_instance_creation_function()
get_pointer_type(class_full_name)
get_pystruct_init_code(cpp_class, obj)
class pybindgen.cppclass.ReferenceCountingFunctionsPolicy(incref_function, decref_function, peekref_function=None)

Bases: pybindgen.cppclass.ReferenceCountingPolicy

get_delete_code(cpp_class)
write_decref(code_block, obj_expr)
write_incref(code_block, obj_expr)
class pybindgen.cppclass.ReferenceCountingMethodsPolicy(incref_method, decref_method, peekref_method=None)

Bases: pybindgen.cppclass.ReferenceCountingPolicy

get_delete_code(cpp_class)
write_decref(code_block, obj_expr)
write_incref(code_block, obj_expr)
class pybindgen.cppclass.ReferenceCountingPolicy

Bases: pybindgen.cppclass.MemoryPolicy

write_decref(code_block, obj_expr)

Write code to decrease the reference code of an object of this class (the real C++ class, not the wrapper). Should only be called if the class supports reference counting, as reported by the attribute CppClass.has_reference_counting.

write_incref(code_block, obj_expr)

Write code to increase the reference code of an object of this class (the real C++ class, not the wrapper). Should only be called if the class supports reference counting, as reported by the attribute CppClass.has_reference_counting.

class pybindgen.cppclass.SmartPointerPolicy

Bases: pybindgen.cppclass.MemoryPolicy

pointer_name = None
pybindgen.cppclass.boost_shared_ptr_instance_creation_function(cpp_class, code_block, lvalue, parameters, construct_type_name)

boost::shared_ptr “instance creation function”; it is called whenever a new C++ class instance needs to be created

Parameters:
  • cpp_class – the CppClass object whose instance is to be created
  • code_block – CodeBlock object on which the instance creation code should be generated
  • lvalue – lvalue expression that should hold the result in the end
  • parameters – stringified list of parameters
  • construct_type_name – actual name of type to be constructed (it is not always the class name, sometimes it’s the python helper class)
pybindgen.cppclass.common_shared_object_return(value, py_name, cpp_class, code_block, type_traits, caller_owns_return, reference_existing_object, type_is_pointer)
pybindgen.cppclass.default_instance_creation_function(cpp_class, code_block, lvalue, parameters, construct_type_name)

Default “instance creation function”; it is called whenever a new C++ class instance needs to be created; this default implementation uses a standard C++ new allocator.

Parameters:
  • cpp_class – the CppClass object whose instance is to be created
  • code_block – CodeBlock object on which the instance creation code should be generated
  • lvalue – lvalue expression that should hold the result in the end
  • parameters – stringified list of parameters
  • construct_type_name – actual name of type to be constructed (it is not always the class name, sometimes it’s the python helper class)
pybindgen.cppclass.get_c_to_python_converter(value, root_module, code_sink)
pybindgen.cppclass.get_python_to_c_converter(value, root_module, code_sink)
pybindgen.cppclass.implement_parameter_custodians_postcall(wrapper)
pybindgen.cppclass.implement_parameter_custodians_precall(wrapper)
pybindgen.cppclass.scan_custodians_and_wards(wrapper)

Scans the return value and parameters for custodian/ward options, converts them to add_custodian_and_ward API calls. Wrappers that implement custodian_and_ward are: CppMethod, Function, and CppConstructor.