<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>PyCXX: Writing Python Extensions in C++</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <h1><a name="h1_title">Writing Python Extensions in C++ with PyCXX</a></h1> <div>Barry Scott <a href="mailto:barry@barrys-emacs.org">barry@barrys-emacs.org</a></div> <h2>Contents</h2> <ul> <li class="contents_h1"><a href="#h1_title">Writing Python Extensions in C++ with PyCXX</a></li> <li><ul> <li class="contents_h2"><a href="#h2_acknowledgments">Acknowledgments</a></li> <li class="contents_h2"><a href="#h2_Overview">Overview</a></li> <li class="contents_h2"><a href="#h2_download">Download and Installation</a></li> <li class="contents_h2"><a href="#h2_example_code">Example code</a></li> <li class="contents_h2"><a href="#limited_api">PyCXX - Supporting Python 3 limited API (PEP-384)</a></li> <li class="contents_h2"><a href="#h2_2to3">PyCXX - Supporting Python 2 and Python 3</a></li> <li class="contents_h2"><a href="#h2_namespaces">Use of namespaces</a></li> <li class="contents_h2"><a href="#h2_objects">Wrapper for standard objects: <CXX/Objects.hxx></a></li> <li class="contents_h2"><a href="#h2_no_pointers">We avoid programming with Python object pointers</a></li> <li class="contents_h2"><a href="#h2_basic_concepts">The basic concept is to wrap Python pointers</a></li> <li class="contents_h2"><a href="#h2_global_methods">global methods</a></li> <li class="contents_h2"><a href="#h2_comparisons">Comparisons</a></li> <li class="contents_h2"><a href="#h2_class_object">Class Object</a></li> <li class="contents_h2"><a href="#h2_python_pointers">Dealing with pointers returned by the Python C API</a></li> </ul></li> <li class="contents_h1"><a href="#h1_basic_types">The Basic Types</a></li> <li><ul> <li class="contents_h2"><a href="#h2_class_type">Class Type</a></li> <li class="contents_h2"><a href="#h2_class_long">Class Long</a></li> <li class="contents_h2"><a href="#h2_class_float">Class Float</a></li> <li class="contents_h2"><a href="#h1_sequences">Sequences</a></li> <li class="contents_h2"><a href="#h2_general_sequences">General sequences</a></li> <li class="contents_h2"><a href="#h2_subscripting">Subscripting</a></li> <li class="contents_h2"><a href="#h2_iterators">Iterators</a></li> <li class="contents_h2"><a href="#h2_class_seqbase">The SeqBase<T> Interface</a></li> <li class="contents_h2"><a href="#h2_class_char_and_string">Classes Char and String</a></li> <li class="contents_h2"><a href="#h2_class_char">The Char interface</a></li> <li class="contents_h2"><a href="#h2_class_string">The String Interface</a></li> <li class="contents_h2"><a href="#h2_class_byte_and_bytes">Classes Byte and Bytes</a></li> <li class="contents_h2"><a href="#h2_class_byte">The Byte interface</a></li> <li class="contents_h2"><a href="#h2_class_bytes">The Bytes Interface</a></li> <li class="contents_h2"><a href="#h2_class_tuple">Class Tuple</a></li> <li class="contents_h2"><a href="#h2_class_tuplen">Class TupleN</a></li> <li class="contents_h2"><a href="#h2_class_list">Class List</a></li> <li class="contents_h2"><a href="#h2_mappings">Mappings</a></li> <li class="contents_h2"><a href="#h2_class_mapbase">The MapBase<T> interface</a></li> <li class="contents_h2"><a href="#h2_class_dict">Class Dict</a></li> <li class="contents_h2"><a href="#h2_class_callable">Clsss Callable.</a></li> <li class="contents_h2"><a href="#h2_class_module">Interface to class Module</a></li> <li class="contents_h2"><a href="#h2_numeric_interface">Numeric interface</a></li> <li class="contents_h2"><a href="#h2_stream_io">Stream I/O</a></li> </ul></li> <li class="contents_h1"><a href="#h1_exceptions">Exceptions</a></li> <li><ul> <li class="contents_h2"><a href="#h2_class_exception">class BaseException and its children</a></li> <li class="contents_h2"><a href="#h2_exceptions_list">List of Exceptions</a></li> <li class="contents_h2"><a href="#h2_exceptions_using">Using Exceptions in extension methods</a></li> <li class="contents_h2"><a href="#h2_exceptions_catching">Catching Exceptions from the Python API or PyCXX.</a></li> <li class="contents_h2"><a href="#h2_exceptions_clearing">How to clear an Exception</a></li> </ul></li> <li class="contents_h1"><a href="#h1_extension_facilities">Extension Facilities</a></li> <li><ul> <li class="contents_h2"><a href="#h2_creating_extention_module">Creating an Python extension module</a></li> <li class="contents_h2"><a href="#h2_creating_extension_type">Creating a Python extension type</a></li> <li class="contents_h2"><a href="#h2_sample_pythonextension">Sample usage of PythonExtension</a></li> <li class="contents_h2"><a href="#h2_type_initialization">Type initialization</a></li> <li class="contents_h2"><a href="#h2_memory_management">Notes on memory management and extension objects</a></li> </ul></li> </ul> <h2><a name="h2_acknowledgments">Acknowledgments</a></h2> <p>Thank you to Geoffrey Furnish for patiently teaching me the finer points of C++ and its template facility, and his critique of PyCXX in particular. With version 4 I welcome Barry Scott as co-author. -- Paul Dubois</p> <p>Paul is no longer contributing to PyCXX. Thanks for all your great work on PyCXX Paul. -- Barry Scott.</p> <h2><a name="h2_Overview">Overview</a></h2> <p>PyCXX is designed to make it easier to extend Python with C++</p> <p>PyCXX Version 6.1 and later supports both Python 2 and Python 3.</p> <p>PyCXX Version 7.1 and later support the <a href="https://www.python.org/dev/peps/pep-0384/">Python 3 limited API (PEP-384).</a></p> <p>PyCXX is a set of C++ facilities to make it easier to write Python extensions. The chief way in which PyCXX makes it easier to write Python extensions is that it greatly increases the probability that your program will not make a reference-counting error and will not have to continually check error returns from the Python C API. PyCXX integrates Python with C++ in these ways: </p> <ul> <li>C++ exception handling is relied on to detect errors and clean up. In a complicated function this is often a tremendous problem when writing in C. With PyCXX, we let the compiler keep track of what objects need to be dereferenced when an error occurs.</li> <li>The Standard Template Library (STL) and its many algorithms plug and play with Python containers such as lists and tuples.</li> <li>The optional CXX/Extensions.hxx facility allows you to replace the clumsy C tables with objects and method calls that define your modules and extension objects.</li> </ul> <h2><a name="h2_download">Download and Installation</a></h2> <p>Download PyCXX from <a href="http://sourceforge.net/projects/cxx/">http://sourceforge.net/projects/cxx/</a>.</p> <p>The distribution layout is:</p> <table cellspacing="0" cellpadding="3px"> <tr><th>Directory</th><th>Description</th></tr> <tr><td class="code">.</td><td>Makefile for Unix and Windows, Release documentation</td></tr> <tr><td class="code">./CXX</td><td>Header files</td></tr> <tr><td class="code">./Src</td><td>Source files</td></tr> <tr><td class="code">./Doc</td><td>Documentation</td></tr> <tr><td class="code">./Demo</td><td>Testing and Demonstartion files</td></tr> </table> <p>To use PyCXX you use its include files and add its source routines to your module.</p> <p>Installation:</p> <ul> <li>Install the PyCXX files into a directory of your choice. For example:<br /> Windows: <cite>C:\PyCXX</cite><br /> Unix: <cite>/usr/local/PyCXX</cite></li> <li>Tell your compiler where the PyCXX header files are:<br /> Windows: <cite>cl /I=C:\PyCXX ...</cite><br /> Unix: <cite>g++ -I/usr/local/PyCXX ...</cite></li> <li>Include PyCXX headers files in your code using the CXX prefix:<br /> <cite>#include "CXX/Objects.hxx"</cite></li> </ul> <p>The header file CXX/config.h may need to be adjusted for the compiler you use. As of this writing, only a fairly obscure reference to part of the standard library needs this adjustment. Unlike prior releases, PyCXX now assumes namespace support and a standard C++ library. </p> <h2><a name="h2_example_code">Example code</a></h2> <p>The Demo directory of the distribution contains examples of how to use many of the facilities in PyCXX.</p> <p>In the top level folder of the PyCXX distributions are a number of makefiles that can be used to build and run the example code.</p> <p>For example on Linux example_linux_py30.mak will build and run the example code.</p> <pre>make -f example_linux_py30.mak clean test</pre> <table cellspacing="0" cellpadding="3px"> <tr><th>Source</th><th>Description</th></tr> <tr><td>Demo/test_simple.py, Demo/simple.cxx</td><td>The simplest code needed to create a module and classes in C++.</td></tr> <tr><td>Demo/test_example.py, Demo/example.cxx</td><td>The original PyCXX example code. It is now the main test suite for PyCXX.</td></tr> <tr><td>Demo/range.hxx, Demo/range.cxx</td><td>Impliments the range object use by example.cxx.</td></tr> </table> <h2><a name="limited_api">PyCXX - Supporting Python 3 limited API (PEP-384)</a></h2> <p>Starting with Python 3.4 and PyCXX 7.1.0 it is possible to create extensions that use the Python limited API. (It was not possible to support Python 3.3)</p> <p>Choose the oldest version of python that you want support and the binary extension will run in that version and all the newer versions.</p> <p>Define Py_LIMITED_API when compiling all your code and the PyCXX code.</p> <p>The value of Py_LIMITED_API is the first python version that you want to support.</p> <p> <ul> <li>Python 3.4 or later: Defined Py_LIMITED_API as 0x03040000 <li>Python 3.5 or later: Defined Py_LIMITED_API as 0x03050000 <li>etc. </ul> <p>Note: Some of the PyCXX API cannot be supported in the Py_LIMITED_API mode. The header files only include classes and functions that can be supported.</p> <h2><a name="h2_2to3">PyCXX - Supporting Python 2 and Python 3</a></h2> <p>It is possible to have common code that can be compiled to work with Python 2 or Python 3.</p> <p>Define PYCXX_PYTHON_2TO3 to turn on the compatibility support. When compiling against Python 2 this means faking up the Python 3 API and when compiling against Python 3 faking the old Python 2 API.</p> <p>The changes from Python 2 to Python 3 that require code changes are:</p> <ul> <li>string is unicode only in Python 3 - Py::String API changed to match python 3 usage</li> <li>byte is for byte date in Python 3 - Py::Bytes added to PyCXX</li> <li>int has been removed - Py::Int has been removed from PyCXX</li> </ul> <p>This means that you will need to:</p> <ul> <li>Replace Py::Nothing with Py::None - required</li> <li>Replace Py::Int with Py::Long - recommended</li> <li>Replace Py::LongLong with Py::Long - recommended</li> <li>Replace as_std_string() with as_std_string( "encoding" ) or as_std_string( NULL ) - required</li> <li>Replace Py::String that holds non unicode data with Py::Bytes - required</li> </ul> <h2><a name="h2_namespaces">Use of namespaces</a></h2> <p>All PyCXX assets are in namespace "Py". You need to include the Py:: prefix when referring to them, or include the statement:</p> <p>using namespace Py;</p> <h2><a name="h2_objects">Wrapper for standard objects: <CXX/Objects.hxx></a></h2> <p>Header file CXX/Objects.hxx requires adding file Src/cxxsupport.cxx and Src/IndirectPythonInterface.cxx to your module sources. CXX/Objects.hxx provides a set of wrapper classes that allow you access to most of the Python C API using a C++ notation that closely resembles Python. For example, this Python:</p> <pre>d = {} d[ "a" ] = 1 d[ "b" ] = 2 alist = d.keys() print alist</pre> <p>Can be written in C++:</p> <pre>Py::Dict d; Py::List alist; d[ "a" ] = Py::Long( 1 ); d[ "b" ] = Py::Long( 2 ); alist = d.keys(); std::cout << alist << std::endl; </pre> <p>You can optionally use the CXX/Extensions.hxx facility described later to define Python extension modules and extension objects.</p> <h2><a name="h2_no_pointers">We avoid programming with Python object pointers</a></h2> <p>The essential idea is that we avoid, as much as possible, programming with pointers to Python objects, that is, variables of type <cite>PyObject *</cite>. Instead, we use instances of a family of C++ classes that represent the usual Python objects. This family is easily extendible to include new kinds of Python objects.</p> <p>For example, consider the case in which we wish to write a method, taking a single integer argument, that will create a Python <cite>dict</cite> and insert into it that the integer plus one under the key <cite>value</cite>. In C we might do that as follows:</p> <pre>static PyObject *mymodule_addvalue( PyObject *args ) { PyObject *d; PyObject *f; int k; PyArgs_ParseTuple( args, "i", &k ); d = PyDict_New(); if( !d ) return NULL; f = PyInt_NEW( k+1 ); if( !f ) { Py_DECREF( d ); /* have to get rid of d first */ return NULL; } if( PyDict_SetItemString( d, "value", f ) == -1 ) { Py_DECREF( f ); Py_DECREF( d ); return NULL; } return d; }</pre> <p>If you have written a significant Python extension, this tedium looks all too familiar. The vast bulk of the coding is error checking and cleanup. Now compare the same thing written in C++ using CXX/Objects.hxx. The things with Python-like names ( Long, Dict, Tuple ) are from CXX/Objects.hxx.</p> <pre>static PyObject *mymodule_addvalue( PyObject *pargs ) { try { Tuple args( pargs ); args.verify_length( 1 ); Dict d; Long k = args[0]; d["value"] = k + 1; return new_reference_to( d ); } catch( const PyException & ) { return NULL; } }</pre> <p>If there are not the right number of arguments or the argument is not an integer, an exception is thrown. In this case we choose to catch it and convert it into a Python exception. The C++ exception handling mechanism takes care all the cleanup.</p> <p>Note that the creation of the <cite>Long k</cite> got the first argument <em>and</em> verified that it is an <cite>Long</cite>.</p> <p>Just to peek ahead, if you wrote this method in an ExtensionModule-derived module of your own, it would be a method and it could be written as:</p> <pre> Object addvalue( const Tuple &args ) { args.verify_length( 1 ); Dict d; Long k = args[0]; d["value"] = k + 1; return d; } </pre> <h2><a name="h2_basic_concepts">The basic concept is to wrap Python pointers</a></h2> <p>The basic concept of CXX/Objects.hxx is to create a wrapper around each <cite>PyObject *</cite> so that the reference counting can be done automatically, thus eliminating the most frequent source of errors. In addition, we can then add methods and operators so that Python objects can be manipulated in C++ much like you would in Python.</p> <p>Each <cite>Object</cite> contains a <cite>PyObject *</cite> to which it owns a reference. When an <cite>Object</cite> is destroyed, it releases its ownership on the pointer. Since C++ calls the destructors on objects that are about to go out of scope, we are guaranteed that we will keep the reference counts right even if we unexpectedly leave a routine with an exception.</p> <p>As a matter of philosophy, CXX/Objects.hxx prevents the creation of instances of its classes unless the instance will be a valid instance of its class. When an attempt is made to create an object that will not be valid, an exception is thrown.</p> <p>Class <cite>Object</cite> represents the most general kind of Python object. The rest of the classes that represent Python objects inherit from it.</p> <pre>Object Type Float Long Complex Char Sequence -> SeqBase<T> String Tuple List Mapping -> MapBase<T> Dict Callable Module</pre> <p>There are several constructors for each of these classes. For example, you can create an <cite>Long</cite> from an integer as in</p> <pre>Long s( 3 )</pre> <p>However, you can also create an instance of one of these classes using any <cite>PyObject *</cite> or another <cite>Object</cite>. If the corresponding Python object does not actually have the type desired, an exception is thrown. This is accomplished as follows. Class <cite>Object</cite> defines a virtual function <cite>accepts</cite>:</p> <pre>virtual bool accepts( PyObject *p )</pre> <p>The base class version of <cite>accepts</cite> returns true for any pointer p except 0. This means we can create an Object using any <cite>PyObject *</cite>, or from any other <cite>Object</cite>. However, if we attempt to create an <cite>Long</cite> from a <cite>PyObject *</cite>, the overridding version of <cite>accepts</cite> in class <cite>Long</cite> will only accept pointers that correspond to Python ints. Therefore if we have a <cite>Tuple t</cite> and we wish to get the first element and be sure it is an <cite>Long</cite>, we do</p> <pre>Long first_element = t[0]</pre> <p>This will not only accomplish the goal of extracting the first element of the <cite>Tuple t</cite>, but it will ensure that the result is an <cite>Long</cite>. If not, an exception is thrown. The exception mechanism is discussed later.</p> <h2><a name="h2_global_methods">global methods</a></h2> <table cellspacing="0" cellpadding="3px"> <caption>global methods</caption> <tr> <th>Returns</th> <th>Name( signature )</th> <th>Comment</th> </tr> <tr><td class="code">Object</td><td class="code">asObject( PyObject *p )</td><td>Convert an owned Python pointer into a PyCXX Object</td></tr> <tr><td class="code">PyObject *</td><td class="code">Null()</td><td>return (PyObject *)NULL</td></tr> <tr><td class="code">PyObject *</td><td class="code">new_reference_to( PyObject *p )</td><td>Increment the reference count of <i>p</i></td></tr> <tr><td class="code">PyObject *</td><td class="code">new_reference_to( const Object &g )</td><td>Increment the reference count of <i>g</i></td></tr> <tr><td class="code">Object</td><td class="code">None()</td><td>Return the Python None opject</td></tr> <tr><td class="code">Object</td><td class="code">True()</td><td>Return the Python True opject</td></tr> <tr><td class="code">Object</td><td class="code">False()</td><td>Return the Python False opject</td></tr> </table> <h2><a name="h2_comparisons">Comparisons</a></h2> <p>PyCXX implements a full set of comparison operators (==, !=, >=, >, < <=) for the PyCXX objects.</p> <table cellspacing="0" cellpadding="3px"> <tr><th>Between</th><th>And</th></tr> <tr><td>Object</td><td>Object</td></tr> <tr><td>Long</td><td>Long</td></tr> <tr><td>Long</td><td>long</td></tr> <tr><td>Long</td><td>int</td></tr> <tr><td>Long</td><td>PY_LONG_LONG</td></tr> <tr><td>Float</td><td>Float</td></tr> <tr><td>Float</td><td>double</td></tr> <tr><td>SeqBasea<T>::iterator</td><td>SeqBase<T>::iterator</td></tr> <tr><td>SeqBase<T>::const_iterator</td><td>SeqBase<T>::const_iterator</td></tr> <tr><td>Sequence::iterator</td><td>Sequence::iterator</td></tr> <tr><td>Sequence::const_iterator</td><td>Sequence::const_iterator</td></tr> <tr><td>MapBase<T>::iterator</td><td>MapBase<T>::iterator</td></tr> <tr><td>MapBase<T>::const_iterator</td><td>MapBase<T>::const_iterator</td></tr> <tr><td>Mapping::iterator</td><td>Mapping::iterator</td></tr> <tr><td>Mapping::const_iterator</td><td>Mapping::const_iterator</td></tr> </table> <h2><a name="h2_class_object">Class Object</a></h2> <p>Class <cite>Object</cite> serves as the base class for the other classes. Its default constructor constructs a <cite>Py_None</cite>, the unique object of Python type <cite>None</cite>. The interface to <cite>Object</cite> consists of a large number of methods corresponding to the operations that are defined for every Python object. In each case, the methods throw an exception if anything goes wrong.</p> <p>There is no method corresponding to <cite>PyObject_SetItem</cite> with an arbitrary Python object as a key. Instead, create an instance of a more specific child of <cite>Object</cite> and use the appropriate facilities.</p> <p>The comparison operators use the Python comparison function to compare values. The method <cite>is</cite> is available to test for absolute identity.</p> <p>A conversion to standard library string type <cite>std::string</cite> is supplied using method <cite>as_string</cite>. Stream output of PyCXX <cite>Object</cite> instances uses this conversion, which in turn uses the Python object's str() representation.</p> <p>All the numeric operators are defined on all possible combinations of <cite>Object</cite>, <cite>long</cite>, and <cite>double</cite>. These use the corresponding Python operators, and should the operation fail for some reason, an exception is thrown.</p> <h2><a name="h2_python_pointers">Dealing with pointers returned by the Python C API</a></h2> <p>Often, <cite>PyObject *</cite> pointers are acquired from some function, particularly functions in the Python C API. If you wish to make an object from the pointer returned by such a function, you need to know if the function returns you an <i>owned</i> or <i>unowned</i> reference. Unowned references are unusual but there are some cases where unowned references are returned.</p> <p>Usually, <cite>Object</cite> and its children acquire a new reference when constructed from a <cite>PyObject *</cite>. This is usually not the right behavior if the reference comes from one of the Python C API calls.</p> <p>If p is an owned reference, you can add the boolean <cite>true</cite> as an extra argument in the creation routine, <cite>Object( p, true )</cite>, or use the function <cite>asObject( p )</cite> which returns an <cite>Object</cite> created using the owned reference. For example, the routine <cite>PyString_FromString</cite> returns an owned reference to a Python string object. You could write:</p> <pre>Object w = asObject( PyString_FromString( "my string" ) );</pre> <p>or using the constructor,</p> <pre>Object w( PyString_FromString( "my string" ), true );</pre> <p>In fact, you would never do this, since PyCXX has a class String and you can just say: </p> <pre>String w( "my string" );</pre> <p>Indeed, since most of the Python C API is similarly embodied in <cite>Object</cite> and its descendents, you probably will not use asObject all that often.</p> <table cellspacing="0" cellpadding="3px"> <caption>Class Object</caption> <tr> <th>Returns</th> <th>Name( signature )</th> <th>Comment</th> </tr> <tr> <td colspan="3"><strong>Basic Methods</strong></td> </tr> <tr> <td class="code">explicit </td> <td class="code">Object( PyObject *pyob=Py_None, bool owned=false ) </td> <td>Construct from pointer. </td> </tr> <tr> <td class="code">explicit</td> <td class="code">Object( const Object &ob )</td> <td>Copycons; acquires an owned reference.</td> </tr> <tr> <td class="code">Object &</td> <td class="code">operator=( const Object &rhs ) </td> <td>Acquires an owned reference.</td> </tr> <tr> <td class="code">Object &</td> <td class="code">operator=( PyObject *rhsp ) </td> <td>Acquires an owned reference.</td> </tr> <tr> <td class="code">virtual</td> <td class="code">~Object() </td> <td>Releases the reference.</td> </tr> <tr> <td class="code">void</td> <td class="code">increment_reference_count() </td> <td>Explicitly increment the count</td> </tr> <tr> <td class="code">void</td> <td class="code">decrement_reference_count()</td> <td>Explicitly decrement count but not to zero</td> </tr> <tr> <td class="code">PyObject*</td> <td class="code">operator*() const</td> <td>Lends the pointer</td> </tr> <tr> <td class="code">PyObject*</td> <td class="code">ptr() const</td> <td>Lends the pointer</td> </tr> <tr> <td class="code">virtual bool</td> <td class="code">accepts( PyObject *pyob ) const</td> <td>Would assignment of pyob to this object succeed?</td> </tr> <tr> <td class="code">std::string</td> <td class="code">as_string() const</td> <td>str() representation</td> </tr> <tr> <td colspan="3"><strong>Python API Interface</strong></td> </tr> <tr> <td class="code">int</td> <td class="code">reference_count() const </td> <td>reference count</td> </tr> <tr> <td class="code">Type</td> <td class="code">type() const</td> <td>associated type object</td> </tr> <tr> <td class="code">String</td> <td class="code">str() const</td> <td>str() representation</td> </tr> <tr> <td class="code">String</td> <td class="code">repr() const</td> <td>repr() representation</td> </tr> <tr> <td class="code">bool</td> <td class="code">hasAttr( const std::string &s ) const</td> <td>hasattr( this, s )</td> </tr> <tr> <td class="code">Object</td> <td class="code">getAttr( const std::string &s ) const</td> <td>getattr( this, s )</td> </tr> <tr> <td class="code">Object</td> <td class="code">getItem( const Object &key ) const</td> <td>getitem( this, key )</td> </tr> <tr> <td class="code">long</td> <td class="code">hashValue() const</td> <td>hash( this )</td> </tr> <tr> <td class="code">void</td> <td class="code">setAttr( const std::string &s,<br />const Object &value )</td> <td>this.s = value</td> </tr> <tr> <td class="code">void</td> <td class="code">delAttr( const std::string &s ) </td> <td>del this.s</td> </tr> <tr> <td class="code">void</td> <td class="code">delItem( const Object &key ) </td> <td>del this[key]</td> </tr> <tr> <td class="code">bool</td> <td class="code">isCallable() const</td> <td>does this have callable behavior?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isList() const</td> <td>is this a Python list?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isMapping() const</td> <td>does this have mapping behaviors?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isNumeric() const</td> <td>does this have numeric behaviors?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isSequence() const </td> <td>does this have sequence behaviors?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isTrue() const</td> <td>is this true in the Python sense?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isType( const Type &t ) const</td> <td>is type( this ) == t?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isTuple() const</td> <td>is this a Python tuple?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isString() const</td> <td>is this a Python string?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isUnicode() const</td> <td>is this a Python Unicode string?</td> </tr> <tr> <td class="code">bool</td> <td class="code">isDict() const</td> <td>is this a Python dictionary?</td> </tr> <tr> <td colspan="3"><strong>Comparison Operators</strong></td> </tr> <tr> <td class="code">bool</td> <td class="code">is( PyObject *pother ) const</td> <td>test for identity</td> </tr> <tr> <td class="code">bool</td> <td class="code">is( const Object &other ) const</td> <td>test for identity</td> </tr> <tr> <td class="code">bool </td> <td class="code">operator==( const Object &o2 ) const</td> <td>Comparisons use Python rich compare</td> </tr> <tr> <td class="code">bool</td> <td class="code">operator!=( const Object &o2 ) const</td> <td>Comparisons use Python rich compare</td> </tr> <tr> <td class="code">bool</td> <td class="code">operator>=( const Object &o2 ) const</td> <td>Comparisons use Python rich compare</td> </tr> <tr> <td class="code">bool</td> <td class="code">operator<=( const Object &o2 ) const </td> <td>Comparisons use Python rich compare</td> </tr> <tr> <td class="code">bool</td> <td class="code">operator<( const Object &o2 ) const</td> <td>Comparisons use Python rich compare</td> </tr> <tr> <td class="code">bool</td> <td class="code">operator>( const Object &o2 ) const</td> <td>Comparisons use Python rich compare</td> </tr> </table> <h1><a name="h1_basic_types">The Basic Types</a></h1> <p>Corresponding to each of the basic Python types is a class that inherits from Object. Here are the interfaces for those types. Each of them inherits from Object and therefore has all of the inherited methods listed for Object. Where a virtual function is overridden in a class, the name is underlined. </p> <h2><a name="h2_class_type">Class Type</a></h2> <p>Class Type corresponds to Python type objects. There is no default constructor.</p> <table cellspacing="0" cellpadding="3px"> <caption>class Type</caption> <tr> <th>Returns</th> <th>Name and Signature</th> <th>Comments</th> </tr> <tr> <td class="code">explicit</td> <td class="code">Type( PyObject *pyob, bool owned = false )</td> <td>Constructor</td> </tr> <tr> <td class="code">explicit</td> <td class="code">Type( const Object &ob )</td> <td>Constructor</td> </tr> <tr> <td class="code">explicit</td> <td class="code">Type( const Type &t )</td> <td>Copycons</td> </tr> <tr> <td class="code">Type&</td> <td class="code">operator=( const Object &rhs ) </td> <td>Assignment</td> </tr> <tr> <td class="code">Type&</td> <td class="code">operator=( PyObject *rhsp ) </td> <td>Assignment</td> </tr> <tr> <td class="code">virtual bool</td> <td class="code">accepts( PyObject *pyob ) const</td> <td>Uses PyType_Check</td> </tr> </table> <h2><a name="h2_class_long">Class Long</a></h2> <p>Class Long, derived publically from Object, corresponds to Python type long. In Python, a long is an integer type of unlimited size. Implicit conversions to both double and long are provided, although the latter may of course fail if the number is actually too big. All constructors are explicit. The default constructor produces a Python long zero.</p> <table cellspacing="0" cellpadding="3px"> <caption>class Long</caption> <tr> <th>Returns</th> <th>Name and Signature</th> <th>Comments</th> </tr> <tr> <td class="code">explicit</td> <td class="code">Long( PyObject *pyob, bool owned = false )</td> <td>Constructor</td> </tr> <tr> <td class="code">explicit</td> <td class="code">Long( const Long &ob )</td> <td>Constructor</td> </tr> <tr> <td class="code">explicit</td> <td class="code">Long( long v = 0L )</td> <td>Construct from long</td> </tr> <tr> <td class="code">explicit</td> <td class="code">Long( int v )</td> <td>Contruct from int</td> </tr> <tr> <td class="code">explicit</td> <td class="code">Long( const Object &ob )</td> <td>Copycons</td> </tr> <tr> <td class="code">Long &</td> <td class="code">operator=( const Object &rhs )</td> <td>Assignment</td> </tr> <tr> <td class="code">Long &</td> <td class="code">operator=( PyObject *rhsp )</td> <td>Assignment</td> </tr> <tr> <td class="code">virtual bool</td> <td class="code">accepts( PyObject *pyob ) const </td> <td>Based on PyLong_Check</td> </tr> <tr> <td class="code">double</td> <td class="code">operator double() const </td> <td><em>Implicit</em> conversion to double</td> </tr> <tr> <td class="code">long</td> <td class="code">operator long() const</td> <td><em>Implicit</em> conversion to long</td> </tr> <tr> <td class="code">Long &</td> <td class="code">operator=( int v )</td> <td>Assign from int</td> </tr> <tr> <td class="code">Long &</td> <td class="code">operator=( long v ) </td> <td>Assign from long</td> </tr> </table> <h2><a name="h2_class_float">Class Float</a></h2> <p>Class Float corresponds to Python floats, which in turn correspond to C double. The default constructor produces the Python float 0.0. </p> <table cellspacing="0" cellpadding="3px"> <caption>class Float</caption> <tr> <th>Returns</th> <th>Name and Signature</th> <th>Comments</th> </tr> <tr> <td class="code">explicit</td> <td class="code">Float( PyObject *pyob, bool owned = false ) </td> <td>Constructor</td> </tr> <tr> <td class="code"></td> <td class="code">Float( const Float &f ) </td> <td>Construct from float</td> </tr> <tr> <td class="code">explicit</td> <td class="code">Float( double v=0.0 )</td> <td>Construct from double</td> </tr> <tr> <td class="code">explicit</td> <td class="code">Float( const Object &ob )</td> <td>Copycons</td> </tr> <tr> <td class="code">Float&</td> <td class="code">operator=( const Object &rhs )</td> <td>Assignment</td> </tr> <tr> <td class="code">Float&</td> <td class="code">operator=( PyObject *rhsp )</td> <td>Assignment</td> </tr> <tr> <td class="code">virtual bool </td> <td class="code">accepts( PyObject *pyob ) const</td> <td>Based on PyFloat_Check</td> </tr> <tr> <td class="code">double </td> <td class="code">operator double() const</td> <td><em>Implicit</em> conversion to double</td> </tr> <tr> <td class="code">Float &</td> <td class="code">operator=( double v )</td> <td>Assign from double</td> </tr> <tr> <td class="code">Float &</td> <td class="code">operator=( int v )</td> <td>Assign from int</td> </tr> <tr> <td class="code">Float &</td> <td class="code">operator=( long v )</td> <td>Assign from long</td> </tr> <tr> <td class="code">Float &</td> <td class="code">operator=( const Long &iob )</td> <td>Assign from Long</td> </tr> </table> <h2><a name="h1_sequences">Sequences</a></h2> <p>PyCXX implements a quite sophisticated wrapper class for Python sequences. While every effort has been made to disguise the sophistication, it may pop up in the form of obscure compiler error messages, so in this documentation we will first detail normal usage and then discuss what is under the hood.</p> <p>The basic idea is that we would like the subscript operator [] to work properly, and to be able to use STL-style iterators and STL algorithms across the elements of the sequence.</p> <p>Sequences are implemented in terms of a templated base class, SeqBase<T>. The parameter T is the answer to the question, sequence of what? For Lists, for example, T is Object, because the most specific thing we know about an element of a List is simply that it is an Object.( Class List is defined below; it is a descendent of Object that holds a pointer to a Python list ). For strings, T is Char, which is a wrapper in turn of Python strings whose length is one.</p> <p>For convenience, the word <strong>Sequence</strong> is a typedef of SeqBase<Object>.</p> <h2><a name="h2_general_sequences">General sequences</a></h2> <p>Suppose you are writing an extension module method that expects the first argument to be any kind of Python sequence, and you wish to return the length of that sequence. You might write:</p> <pre>static PyObject* my_module_seqlen( PyObject *args ) { try { Tuple t( args ); // set up a Tuple pointing to the arguments. if( t.length() != 1 ) throw PyException( "Incorrect number of arguments to seqlen." ); Sequence s = t[0]; // get argument and be sure it is a sequence return new_reference_to( Long( s.length() ) ); } catch( const PyException &) { return Py_Null; } }</pre> <p>As we will explain later, the try/catch structure converts any errors, such as the first argument not being a sequence, into a Python exception.</p> <h2><a name="h2_subscripting">Subscripting</a></h2> <p>When a sequence is subscripted, the value returned is a special kind of object which serves as a proxy object. The general idea of proxy objects is discussed in Scott Meyers' book, "More Effective C++". Proxy objects are necessary because when one subscripts a sequence it is not clear whether the value is to be used or the location assigned to. Our proxy object is even more complicated than normal because a sequence reference such as s[i] is not a direct reference to the i'th object of s. </p> <p>In normal use, you are not supposed to notice this magic going on behind your back. You write:</p> <pre>Object t; Sequence s; s[2] = t + s[1]</pre> <p>and here is what happens: s[1] returns a proxy object. Since there is no addition operator in Object that takes a proxy as an argument, the compiler decides to invoke an automatic conversion of the proxy to an Object, which returns the desired component of s. The addition takes place, and then there is an assignment operator in the proxy class created by the s[2], and that assignment operator stuffs the result into the 2 component of s.</p> <p>It is possible to fool this mechanism and end up with a compiler failing to admit that a s[i] is an Object. If that happens, you can work around it by writing Object( s[i] ), which makes the desired implicit conversion, explicit.</p> <h2><a name="h2_iterators">Iterators</a></h2> <p>Each sequence class provides the following interface. The class seqref<T> is the proxy class. We omit the details of the iterator, const_iterator, and seqref<T> here. See CXX/Objects.hxx if necessary. The purpose of most of this interface is to satisfy requirements of the STL.</p> <h2><a name="h2_class_seqbase">The SeqBase<T> Interface</a></h2> <p>SeqBase<T> inherits from Object.</p> <table cellspacing="0" cellpadding="3px"> <caption>class SeqBase>T<</caption> <tr> <th>Type</th> <th>Name</th> </tr> <tr> <td class="code">typedef int </td> <td class="code">size_type</td> </tr> <tr> <td class="code">typedef seqref<T></td> <td class="code">reference</td> </tr> <tr> <td class="code">typedef T </td> <td class="code">const_reference</td> </tr> <tr> <td class="code">typedef seqref<T>*</td> <td class="code">pointer</td> </tr> <tr> <td class="code">typedef int </td> <td class="code">difference_type</td> </tr> <tr> <td class="code">virtual size_type</td> <td class="code">max_size() const</td> </tr> <tr> <td class="code">virtual size_type </td> <td class="code">capacity() const;</td> </tr> <tr> <td class="code">virtual void </td> <td class="code">swap( SeqBase<T> &c );</td> </tr> <tr> <td class="code">virtual size_type </td> <td class="code">size() const;</td> </tr> <tr> <td class="code">explicit </td> <td class="code">SeqBase<T>();</td> </tr> <tr> <td class="code">explicit </td> <td class="code">SeqBase<T>( PyObject *pyob, bool owned = false );</td> </tr> <tr> <td class="code">explicit </td> <td class="code">SeqBase<T>( const Object &ob );</td> </tr> <tr> <td class="code">SeqBase<T> &</td> <td class="code">operator=( const Object &rhs );</td> </tr> <tr> <td class="code">SeqBase<T> &</td> <td class="code">operator=( PyObject *rhsp );</td> </tr> <tr> <td class="code">virtual bool </td> <td class="code">accepts( PyObject *pyob ) const;</td> </tr> <tr> <td class="code">size_type </td> <td class="code">length() const ;</td> </tr> <tr> <td class="code">const T </td> <td class="code">operator[]( size_type index ) const; </td> </tr> <tr> <td class="code">seqref<T> </td> <td class="code">operator[]( size_type index ); </td> </tr> <tr> <td class="code">virtual T </td> <td class="code">getItem( size_type i ) const;</td> </tr> <tr> <td class="code">virtual void </td> <td class="code">setItem( size_type i, const T &ob );</td> </tr> <tr> <td class="code">SeqBase<T> </td> <td class="code">repeat( int count ) const;</td> </tr> <tr> <td class="code">SeqBase<T> </td> <td class="code">concat( const SeqBase<T> &other ) const ;</td> </tr> <tr> <td class="code">const T </td> <td class="code">front() const;</td> </tr> <tr> <td class="code">seqref<T> </td> <td class="code">front();</td> </tr> <tr> <td class="code">const T </td> <td class="code">back() const;</td> </tr> <tr> <td class="code">seqref<T> </td> <td class="code">back(); </td> </tr> <tr> <td class="code">void </td> <td class="code">verify_length( size_type required_size );</td> </tr> <tr> <td class="code">void </td> <td class="code">verify_length( size_type min_size, size_type max_size );</td> </tr> <tr> <td class="code">class</td> <td class="code">iterator;</td> </tr> <tr> <td class="code">iterator </td> <td class="code">begin(); </td> </tr> <tr> <td class="code">iterator </td> <td class="code">end();</td> </tr> <tr> <td class="code">class </td> <td class="code">const_iterator;</td> </tr> <tr> <td class="code">const_iterator </td> <td class="code">begin() const;</td> </tr> <tr> <td class="code">const_iterator </td> <td class="code">end() const;</td> </tr> </table> <p>Any heir of class Object that has a sequence behavior should inherit from class SeqBase<T>, where T is specified as the type of object that represents the individual elements of the sequence. The requirements on T are that it has a constructor that takes a PyObject *as an argument, that it has a default constructor, a copy constructor, and an assignment operator. In short, any properly defined heir of Object will work. </p> <h2><a name="h2_class_char_and_string">Classes Char and String</a></h2> <p>Python strings are unusual in that they are immutable sequences of characters. However, there is no character type per se; rather, when subscripted strings return a string of length one. To simulate this, we define two classes Char and String. The Char class represents a Python string object of length one. The String class represents a Python string, and its elements make up a sequence of Char's.</p> <p>The user interface for Char is limited. Unlike String, for example, it is not a sequence.</p> <h2><a name="h2_class_char">The Char interface</a></h2> <p>Char inherits from Object. Char holds a single Unicode character.</p> <p>unicodestring is a typedef for std::basic_string<Py_UNICODE></p> <table cellspacing="0" cellpadding="3px"> <caption>class Char</caption> <tr> <th>Type</th> <th>Name</th> </tr> <tr> <td class="code">explicit</td> <td class="code">Char( PyObject *pyob, bool owned = false )</td> </tr> <tr> <td class="code"></td> <td class="code">Char( const Object &ob )</td> </tr> <tr> <td class="code"></td> <td class="code">Char( int v )</td> </tr> <tr> <td class="code"></td> <td class="code">Char( Py_UNICODE v )</td> </tr> <tr> <td class="code"></td> <td class="code">Char( const unicodestring &v )</td> </tr> <tr> <td class="code">Char &</td> <td class="code">operator=( const Object &o ) </td> </tr> <tr> <td class="code">Char &</td> <td class="code">operator=( PyObject *p ) </td> </tr> <tr> <td class="code">Char &</td> <td class="code">operator=( int v ) </td> </tr> <tr> <td class="code">Char &</td> <td class="code">operator=( Py_UNICODE v ) </td> </tr> <tr> <td class="code">Char &</td> <td class="code">operator=( unicodestring &v ) </td> </tr> <tr> <td class="code"></td> <td class="code">operator String() const</td> </tr> </table> <h2><a name="h2_class_string">The String Interface</a></h2> <p>String inherits from SeqBase<Char>. String holds a sequence of Unicode characters.</p> <p>The following is taken from Pythons's unicode.h. </p> <p>Many of these APIs take two arguments encoding and errors. These parameters encoding and errors have the same semantics as the ones of the builtin unicode() API. </p> <p>Setting encoding to NULL causes the default encoding to be used. </p> <p>Error handling is set by errors which may also be set to NULL meaning to use the default handling defined for the codec. Default error handling for all builtin codecs is "strict" (ValueErrors are raised). </p> <p>The codecs all use a similar interface. Only deviation from the generic ones are documented. </p> <table cellspacing="0" cellpadding="3px"> <caption>class String</caption> <tr> <th>Type</th> <th>Name</th> </tr> <tr> <td class="code">explicit </td> <td class="code">String( PyObject *pyob, bool owned = false )</td> </tr> <tr> <td class="code"> </td> <td class="code">String( const Object &ob )</td> </tr> <tr> <td class="code"> </td> <td class="code">String()</td> </tr> <tr> <td class="code"> </td> <td class="code">String( const char *latin1 )</td> </tr> <tr> <td class="code"> </td> <td class="code">String( const char *latin1, Py_ssize_t size )</td> </tr> <tr> <td class="code"> </td> <td class="code">String( const std::string &latin1 )</td> </tr> <tr> <td class="code"> </td> <td class="code">String( const std::string &v, const char *encoding, const char *error=NULL )</td> </tr> <tr> <td class="code"> </td> <td class="code">String( const char *s, const char *encoding, const char *error=NULL )</td> </tr> <tr> <td class="code"> </td> <td class="code">String( const char *s, Py_ssize_t len, const char *encoding, const char *error=NULL )</td> </tr> <tr> <td class="code">String &</td> <td class="code">operator=( const Object &o ) </td> </tr> <tr> <td class="code">String &</td> <td class="code">operator=( PyObject *p ) </td> </tr> <tr> <td class="code">String &</td> <td class="code">operator=( const unicodestring &v ) </td> </tr> <tr> <td class="code">size_type</td> <td class="code">size() const</td> </tr> <tr> <td class="code">size_type</td> <td class="code">capacity() const</td> </tr> <tr> <td class="code">unicodestring</td> <td class="code">as_unicodestring() const</td> </tr> <tr> <td class="code">std::string</td> <td class="code">operator std::string() const</td> </tr> <tr> <td class="code">String</td> <td class="code">encode( const char *encoding, const char *error="strict" )</td> </tr> <tr> <td class="code">std::string</td> <td class="code">as_std_string( const char *encoding=NULL, const char *error="strict" ) const</td> </tr> </table> <h2><a name="h2_class_byte_and_bytes">Classes Byte and Bytes</a></h2> <p>Bytes corresponds to the Python type byte.</p> <h2><a name="h2_class_byte">The Byte interface</a></h2> <p>Byte inherits from Object. Byte holds a single 8-bit byte of data.</p> <table cellspacing="0" cellpadding="3px"> <caption>class Byte</caption> <tr> <th>Type</th> <th>Name</th> </tr> <tr> <td class="code">explicit</td> <td class="code">Byte( PyObject *pyob, bool owned = false )</td> </tr> <tr> <td class="code"></td> <td class="code">Byte( const Object &ob )</td> </tr> <tr> <td class="code"></td> <td class="code">Byte( const std::string &v )</td> </tr> <tr> <td class="code"></td> <td class="code">Byte( char v )</td> </tr> <tr> <td class="code">Byte &</td> <td class="code">operator=( const Object &o ) </td> </tr> <tr> <td class="code">Byte &</td> <td class="code">operator=( PyObject *p ) </td> </tr> <tr> <td class="code">Byte &</td> <td class="code">operator=( const std::string &v ) </td> </tr> <tr> <td class="code">Byte &</td> <td class="code">operator=( char v ) </td> </tr> <tr> <td class="code"></td> <td class="code">operator Bytes() const</td> </tr> </table> <h2><a name="h2_class_bytes">The Bytes Interface</a></h2> <p>Bytes inherits from SeqBase<Byte>. Bytes holds a sequence of 8-bit data.</p> <table cellspacing="0" cellpadding="3px"> <caption>class Bytes</caption> <tr> <th>Type</th> <th>Name</th> </tr> <tr> <td class="code">explicit </td> <td class="code">Bytes( PyObject *pyob, bool owned = false )</td> </tr> <tr> <td class="code"> </td> <td class="code">Bytes( const Object &ob )</td> </tr> <tr> <td class="code"> </td> <td class="code">Bytes()</td> </tr> <tr> <td class="code"> </td> <td class="code">Bytes( const char *v )</td> </tr> <tr> <td class="code"> </td> <td class="code">Bytes( const char *v, Py_ssize_t size )</td> </tr> <tr> <td class="code"> </td> <td class="code">Bytes( const std::string &v )</td> </tr> <tr> <td class="code"> </td> <td class="code">Bytes( const std::string &v, Py_ssize_t size )</td> </tr> <tr> <td class="code"> </td> <td class="code">Bytes( const char *v )</td> </tr> <tr> <td class="code"> </td> <td class="code">Bytes( const char *v, Py_ssize_t size )</td> </tr> <tr> <td class="code">Bytes &</td> <td class="code">operator=( const Object &o ) </td> </tr> <tr> <td class="code">Bytes &</td> <td class="code">operator=( PyObject *p ) </td> </tr> <tr> <td class="code">Bytes &</td> <td class="code">operator=( const std::string &v ) </td> </tr> <tr> <td class="code">size_type</td> <td class="code">size() const</td> </tr> <tr> <td class="code">size_type</td> <td class="code">capacity() const</td> </tr> <tr> <td class="code">String</td> <td class="code">decode( const char *encoding, const char *error="strict" )</td> </tr> <tr> <td class="code">std::string</td> <td class="code">operator std::string() const</td> </tr> <tr> <td class="code">Bytes</td> <td class="code">encode( const char *encoding, const char *error="strict" )</td> </tr> <tr> <td class="code">std::string</td> <td class="code">as_std_string() const</td> </tr> </table> <h2><a name="h2_class_tuple">Class Tuple</a></h2> <p>Class Tuple represents Python tuples. A Tuple is a Sequence. There are two kinds of constructors: one takes a PyObject *as usual, the other takes an integer number as an argument and returns a Tuple of that length, each component initialized to Py_None. The default constructor produces an empty Tuple. </p> <p>Tuples are not immutable, but attempts to assign to their components will fail if the reference count is not 1. That is, it is safe to set the elements of a Tuple you have just made, but not thereafter.</p> <p>Example: create a Tuple containing( 1, 2, 4 )</p> <pre>Tuple t( 3 ); t[0] = Long( 1 ); t[1] = Long( 2 ); t[2] = Long( 4 );</pre> <p>Example: create a Tuple from a list:</p> <pre>Dict d ... Tuple t( d.keys() )</pre> <p>Tuple inherits from Sequence.. Special run-time checks prevent modification if the reference count is greater than one.</p> <table cellspacing="0" cellpadding="3px"> <caption>class Tuple</caption> <tr> <th>Type</th> <th>Name</th> <th>Comment</th> </tr> <tr> <td class="code">virtual void</td> <td class="code">setItem( int offset, const Object &ob ) </td> <td>setItem is overridden to handle tuples properly. </td> </tr> <tr> <td class="code">explicit</td> <td class="code">Tuple( PyObject *pyob, bool owned = false )</td> <td></td> </tr> <tr> <td class="code"> </td> <td class="code">Tuple( const Object &ob )</td> <td></td> </tr> <tr> <td class="code">explicit</td> <td class="code">Tuple( int size = 0 )</td> <td>Create a tuple of the given size. Items initialize to Py_None. Default is an empty tuple.</td> </tr> <tr> <td class="code">explicit</td> <td class="code">Tuple( const Sequence &s )</td> <td>Create a tuple from any sequence.</td> </tr> <tr> <td class="code">Tuple&</td> <td class="code">operator=( const Object &rhs )</td> <td></td> </tr> <tr> <td class="code">Tuple&</td> <td class="code">operator=( PyObject *rhsp )</td> <td></td> </tr> <tr> <td class="code">Tuple</td> <td class="code">getSlice( int i, int j ) const </td> <td>Equivalent to python's t[i:j]</td> </tr> </table> <h2><a name="h2_class_tuplen">Class TupleN</a></h2> <p>Class TupleN is an easy way to make a Tuple of N items.</p> <p>Example: create a Tuple containing( 1, 2, 4 )</p> <pre>TupleN t3( Long( 1 ), Long( 2 ), Long( 3 ) ); </pre> <p>Example: create a Tuple containing( "Hello", "World" )</p> <pre>TupleN t2( String( "Hello" ), String( "Hello" ) ); </pre> <table cellspacing="0" cellpadding="3px"> <caption>class TupleN</caption> <tr> <th>Type</th> <th>Name</th> <th>Comment</th> </tr> <tr> <td class="code"> </td> <td class="code">TupleN() </td> <td>Tuple of 0 elements</td> </tr> <tr> <td class="code"> </td> <td class="code">TupleN( const Object &ob1 ) </td> <td>Tuple of 1 element</td> </tr> <tr> <td class="code"> </td> <td class="code">TupleN( const Object &ob1, const Object &ob2 ) </td> <td>Tuple of 2 elements</td> </tr> <tr> <td class="code"> </td> <td class="code">TupleN( const Object &ob1, const Object &ob2, const Object &ob3 ) </td> <td>Tuple of 3 elements</td> </tr> <tr> <td class="code"> </td> <td class="code">TupleN( const Object &ob1, const Object &ob2, const Object &ob3,<br />         const Object &ob4 ) </td> <td>Tuple of 4 elements</td> </tr> <tr> <td class="code"> </td> <td class="code">TupleN( const Object &ob1, const Object &ob2, const Object &ob3,<br />         const Object &ob4, const Object &ob5 ) </td> <td>Tuple of 5 elements</td> </tr> <tr> <td class="code"> </td> <td class="code">TupleN( const Object &ob1, const Object &ob2, const Object &ob3,<br />         const Object &ob4, const Object &ob5, const Object &ob6 ) </td> <td>Tuple of 6 elements</td> </tr> <tr> <td class="code"> </td> <td class="code">TupleN( const Object &ob1, const Object &ob2, const Object &ob3,<br />         const Object &ob4, const Object &ob5, const Object &ob6,<br />         const Object &ob7 ) </td> <td>Tuple of 7 elements</td> </tr> <tr> <td class="code"> </td> <td class="code">TupleN( const Object &ob1, const Object &ob2, const Object &ob3,<br />         const Object &ob4, const Object &ob5, const Object &ob6,<br />         const Object &ob7, const Object &ob8 ) </td> <td>Tuple of 8 elements</td> </tr> <tr> <td class="code"> </td> <td class="code">TupleN( const Object &ob1, const Object &ob2, const Object &ob3,<br />         const Object &ob4, const Object &ob5, const Object &ob6,<br />         const Object &ob7, const Object &ob8, const Object &ob9 ) </td> <td>Tuple of 9 elements</td> </tr> </table> <h2><a name="h2_class_list">Class List</a></h2> <p>Class List represents a Python list, and the methods available faithfully reproduce the Python API for lists. A List is a Sequence.</p> <p>List inherits from Sequence.</p> <table cellspacing="0" cellpadding="3px"> <caption>class List</caption> <tr> <th>Type</th> <th>Name</th> <th>Comment</th> </tr> <tr> <td class="code">explicit</td> <td class="code">List( PyObject *pyob, bool owned = false )</td> <td></td> </tr> <tr> <td class="code"> </td> <td class="code">List( const Object &ob )</td> <td></td> </tr> <tr> <td class="code"> </td> <td class="code">List( int size = 0 )</td> <td>Create a list of the given size. Items initialized to Py_None. Default is an empty list.</td> </tr> <tr> <td class="code"> </td> <td class="code">List( const Sequence &s )</td> <td>Create a list from any sequence.</td> </tr> <tr> <td class="code">List&</td> <td class="code">operator=( const Object &rhs )</td> <td></td> </tr> <tr> <td class="code">List&</td> <td class="code">operator=( PyObject *rhsp )</td> <td></td> </tr> <tr> <td class="code">List</td> <td class="code">getSlice( int i, int j ) const</td> <td></td> </tr> <tr> <td class="code">void</td> <td class="code">setSlice( int i, int j, const Object &v ) </td> <td></td> </tr> <tr> <td class="code">void</td> <td class="code">append( const Object &ob )</td> <td></td> </tr> <tr> <td class="code">void</td> <td class="code">insert( int i, const Object &ob )</td> <td></td> </tr> <tr> <td class="code">void</td> <td class="code">sort()</td> <td>Sorts the list in place, using Python's member function. You can also use the STL sort function on any List instance.</td> </tr> <tr> <td class="code">void</td> <td class="code">reverse()</td> <td>Reverses the list in place, using Python's member function.</td> </tr> </table> <h2><a name="h2_mappings">Mappings</a></h2> <p>A class MapBase<T> is used as the base class for Python objects with a mapping behavior. The key behavior of this class is the ability to set and use items by subscripting with strings. A proxy class mapref<T> is defined to produce the correct behavior for both use and assignment.</p> <p>For convenience, <cite>Mapping</cite> is a typedef for <cite>MapBase<Object></cite>.</p> <h2><a name="h2_class_mapbase">The MapBase<T> interface</a></h2> <p>MapBase<T> inherits from Object. T should be chosen to reflect the kind of element returned by the mapping.</p> <table cellspacing="0" cellpadding="3px"> <caption>class MapBase<T></caption> <tr> <th>Type</th> <th>Name</th> <th>Comment</th> </tr> <tr> <td class="code">T</td> <td class="code">operator[]( const std::string &key ) const</td> <td></td> </tr> <tr> <td class="code">mapref<T> </td> <td class="code">operator[]( const std::string &key )</td> <td></td> </tr> <tr> <td class="code">int</td> <td class="code">length() const</td> <td>Number of entries.</td> </tr> <tr> <td class="code">int</td> <td class="code">hasKey( const std::string &s ) const </td> <td>Is m[s] defined?</td> </tr> <tr> <td class="code">T</td> <td class="code">getItem( const std::string &s ) const</td> <td>m[s]</td> </tr> <tr> <td class="code">virtual void</td> <td class="code">setItem( const std::string &s, const Object &ob )</td> <td>m[s] = ob</td> </tr> <tr> <td class="code">void</td> <td class="code">delItem( const std::string &s )</td> <td>del m[s]</td> </tr> <tr> <td class="code">void</td> <td class="code">delItem( const Object &s )</td> <td></td> </tr> <tr> <td class="code">List</td> <td class="code">keys() const</td> <td>A list of the keys.</td> </tr> <tr> <td class="code">List</td> <td class="code">values() const</td> <td>A list of the values.</td> </tr> <tr> <td class="code">List</td> <td class="code">items() const</td> <td>Each item is a key-value pair.</td> </tr> </table> <h2><a name="h2_class_dict">Class Dict</a></h2> <p>Class Dict represents Python dictionarys. A Dict is a Mapping. Assignment to subscripts can be used to set the components.</p> <pre>Dict d d["Paul Dubois"] = "( 925 )-422-5426"</pre> <p>Dict inherits from MapBase<Object>.</p> <table cellspacing="0" cellpadding="3px"> <caption>class Dict</caption> <tr> <th>Type</th> <th>Name</th> <th>Comment</th> </tr> <tr> <td class="code">explicit</td> <td class="code">Dict( PyObject *pyob, bool owned = false )</td> <td></td> </tr> <tr> <td class="code"> </td> <td class="code">Dict( const Dict &ob )</td> <td></td> </tr> <tr> <td class="code"> </td> <td class="code">Dict() </td> <td>Creates an empty dictionary</td> </tr> <tr> <td class="code">Dict&</td> <td class="code">operator=( const Object &rhs )</td> <td></td> </tr> <tr> <td class="code">Dict&</td> <td class="code">operator=( PyObject *rhsp )</td> <td></td> </tr> </table> <h2><a name="h2_class_callable">Clsss Callable.</a></h2> <p>Class Callable provides an interface to those Python objects that support a call method. Class Module holds a pointer to a module. If you want to create an extension module, however, see the extension facility. There is a large set of numeric operators.</p> <table cellspacing="0" cellpadding="3px"> <caption>class Callable</caption> <tr><th>Type</th><th>Name</th><th>Comment</th></tr> <tr><td class="code">explicit</td><td class="code">Callable( PyObject *pyob, bool owned = false )</td><td></td></tr> <tr><td class="code">Callable &</td><td class="code">operator=( const Object &rhs )</td><td></td></tr> <tr><td class="code">Callable &</td><td class="code">operator=( PyObject *rhsp )</td><td></td></tr> <tr><td class="code">Object</td><td class="code">apply( const Tuple &args ) const</td><td>Call the object with the given positional arguments</td></tr> <tr><td class="code">Object</td><td class="code">apply( const Tuple &args, const Dict &kwd ) const</td><td>Call the object with the given positional and keyword arguments </td></tr> <tr><td class="code">Object</td><td class="code">apply( PyObject *pargs = 0 ) const </td><td>Call the object with args as the arguments. Checks that pargs is a tuple.</td></tr> </table> <h2><a name="h2_class_module">Interface to class Module</a></h2> <table cellspacing="0" cellpadding="3px"> <caption>class Module</caption> <tr> <th>Type</th> <th>Name</th> <th>Comment</th> </tr> <tr> <td class="code">explicit</td> <td class="code">Module( PyObject *pyob, bool owned = false )</td> <td></td> </tr> <tr> <td class="code">explicit</td> <td class="code">Module( const std::string name )</td> <td>Construct from name of module; does the import if needed.</td> </tr> <tr> <td class="code"></td> <td class="code">Module( const Module &ob ) </td> <td>Copy constructor</td> </tr> <tr> <td class="code">Module&</td> <td class="code">operator=( const Object &rhs ) </td> <td>Assignment</td> </tr> <tr> <td class="code">Module&</td> <td class="code">operator=( PyObject *rhsp ) </td> <td>Assignment</td> </tr> </table> <h2><a name="h2_numeric_interface">Numeric interface</a></h2> <p>Unary operators for plus and minus, and binary operators +, -, *, /, and % are defined for pairs of objects and for objects with scalar integers or doubles( in either order ). Functions abs( ob ) and coerce( o1, o2 ) are also defined. </p> <p>The signature for coerce is:</p> <pre>inline std::pair<Object,Object> coerce( const Object &a, const Object &b )</pre> <p>Unlike the C API function, this simply returns the pair after coercion.</p> <h2><a name="h2_stream_io">Stream I/O</a></h2> <p>Any object can be printed using stream I/O, using std::ostream &operator<< ( std::ostream &os, const Object &ob ). The object's str() representation is converted to a standard string which is passed to std::ostream &operator<< ( std::ostream &os, const std::string &).</p> <h1><a name="h1_exceptions">Exceptions</a></h1> <p>All the standard python exceptions have a C++ equivilent that can to caught and thrown.</p> <p>In addition new expections can be defined using PyCXX as well.</p> <p>Exceptions thrown from C++ will be converted into Python exceptions when returning to Python code.</p> <p>Python exceptions are converted into C++ exceptions when returning from Python code back into C++ code.</p> <h2><a name="h2_class_exception">class BaseException and its children</a></h2> <p>All the Python standard exceptions are provided as C++ classes. The C++ class hierarchy mirrors the Python class hierarchy. The base of the exception hierarchy is class BaseException.</p> The derived exception class, such as IndexError, RuntimeError and ValueError, has a constructor which takes an explanatory string as an argument, and is used in a throw statement such as:</p> <pre>throw IndexError( "Index too large in MyObject access." );</pre> <p>You cannot throw BaseException, but you can catch it.</p> <p>See the Python documentation for a list of all the standard exceptions.</p> <h2><a name="h2_exceptions_list">List of Exceptions</a></h2> <p>The exception hierarchy mirrors the Python exception hierarchy. The concrete exception classes are shown here. With ValueError being the pattern for all the other expections.</p> <table cellspacing="0" cellpadding="3px"> <caption>BaseException</caption> <tr> <th>Type</th> <th>Interface for class Exception</th> </tr> <tr> <td class="code">explicit </td> <td class="code">BaseException()</td> </tr> <tr> <td class="code"> </td> <td class="code">BaseException( const std::string &reason ) </td> </tr> <tr> <td class="code"> </td> <td class="code">BaseException( PyObject *exception, const std::string &reason ) </td> </tr> <tr> <td class="code">void </td> <td class="code">clear()</td> </tr> </table> <table> <caption>Python Standard Exceptions</caption> <tr> <th>Type</th> <th>Interface for class Exception</th> </tr> <tr> <td class="code">void </td> <td class="code"><i>python-standard-exception</i>( const std::string &reason )</td> </tr> </table> <h2><a name="h2_exceptions_using">Using Exceptions in extension methods</a></h2> <p>The exception facility allows you to integrate the C++ and Python exception mechanisms. To do this, you must use the style described below when writing module methods in the old C style. </p> <p>Note: If using the ExtensionModule or PythonExtension mechanisms described below, the method handlers include exception handling so that you only need to use exceptions explicitly in unusual cases.</p> <h2><a name="h2_exceptions_catching">Catching Exceptions from the Python API or PyCXX.</a></h2> <p>In the example, some_method, any expections raise from the C++ will be automatically converted into Python exceptions.</p> <pre>Object some_method( Object &args ) { Tuple a( args ); // we know args is a Tuple if( a.length() != 2 ) { throw AttributeError( "2 arguments expected" ); } // do something useful // and return a result return result; } </pre> <p>And in this example the call_python method is calling back into python and handling ArithmeticError from the "func". Any other expections will be passed back to Python.</p> <pre>Object cal_python( Object &args ) { Tuple a( args ); // we know args is a Tuple Callable func( a[0] ); // first arg expected to be a python callable ... Tuple call_args( 1 ); call_args[0] = Long( 42 ); try { Object result = func.apply( call_args ); } catch( ArithmeticError &e ) { // handle error e.clear(); } return result; } </pre> <h2><a name="h2_exceptions_clearing">How to clear an Exception</a></h2> <p>If you anticipate that an Exception may be thrown and wish to recover from it then add a try/catch block for the expected exception. Then use the method clear() to tell python that the expection has been handled.</p> <pre>catch( ValueError &e ) { // handle expection e.clear(); } </pre> <h1><a name="h1_extension_facilities">Extension Facilities</a></h1> <p>CXX/Extensions.hxx provides facilities for: </p> <ul> <li>Creating a Python extension module</li> <li>Creating new Python extension types</li> </ul> <p>These facilities use CXX/Objects.hxx and its support file cxxsupport.cxx.</p> <p>If you use CXX/Extensions.hxx you must also include source files cxxextensions.c and cxx_extensions.cxx</p> <h2><a name="h2_creating_extention_module">Creating an Python extension module</a></h2> <p>The usual method of creating a Python extension module is to declare and initialize its method table in C. This requires knowledge of the correct form for the table and the order in which entries are to be made into it, and requires casts to get everything to compile without warning. The PyCXX header file CXX/Extensions.h offers a simpler method. Here is a sample usage, in which a module named "example" is created. Note that two details are necessary: </p> <ul> <li>The initialization function must be declared to have external C linkage and to have the expected name. This is a requirement imposed by Python</li> <li>The ExtensionModule object must have a storage class that survives the call to the initialization function. This is most easily accomplished by using a static local inside the initialization function, as in initexample below.</li> </ul> <p>To create an extension module, you inherit from class ExtensionModule templated on yourself: In the constructor, you make calls to register methods of this class with Python as extension module methods. In this example, two methods are added( this is a simplified form of the example in Demo/example.cxx ):</p> <pre>class example_module : public ExtensionModule<example_module> { public: example_module() : ExtensionModule<example_module>( "example" ) { add_varargs_method( "sum", &example_module::ex_sum, "sum( arglist ) = sum of arguments" ); add_varargs_method( "test", &example_module::ex_test, "test( arglist ) runs a test suite" ); initialize( "documentation for the example module" ); } virtual ~example_module() {} private: Object ex_sum( const Tuple &a ) { ... } Object ex_test( const Tuple &a ) { ... } }; </pre> <p>To initialize the extension, you just instantiate one static instance( static so it does not destroy itself! ):</p> <pre>void initexample() { static example_module* example = new example_module; }</pre> <p>The methods can be written to take Tuples as arguments and return Objects. If exceptions occur they are trapped for you and a Python exception is generated. So, for example, the implementation of ex_sum might be:</p> <pre>Object ex_sum( const Tuple &a ) { Float f( 0.0 ); for( int i = 0; i < a.length(); i++ ) { Float g( a[i] ); f = f + g; } return f; }</pre> <p>class ExtensionModule contains methods to return itself as a Module object, or to return its dictionary.</p> <table cellspacing="0" cellpadding="3px"> <caption>class ExtensionModule</caption> <tr> <th>Type</th> <th>Name</th> <th>Comment</th> </tr> <tr> <td class="code">explicit</td> <td class="code">ExtensionModule( char* name ) </td> <td>Create an extension module named "name"</td> </tr> <tr> <td class="code">virtual </td> <td class="code">~ExtensionModule() </td> <td>Destructor</td> </tr> <tr> <td class="code">Dict</td> <td class="code">moduleDictionary() const</td> <td>Returns the module dictionary; module must be initialized.</td> </tr> <tr> <td class="code">Module</td> <td class="code">module() const</td> <td>This module as a Module.</td> </tr> <tr> <td class="code">void </td> <td class="code">add_varargs_method( char *name, method_varargs_function_t method, char *documentation="" )</td> <td>Add a method to the module.</td> </tr> <tr> <td class="code">void </td> <td class="code">add_keyword_method( char *name, method_keyword_function_t method, char *documentation=""</td> <td>Add a method that takes keywords</td> </tr> <tr> <td class="code">void</td> <td class="code">initialize()( protected, call from constructor )</td> <td>Initialize the module once all methods have been added. </td> </tr> </table> <p>The signatures above are:</p> <pre>typedef Object( T::*method_varargs_function_t )( const Tuple &args ); typedef Object( T::*method_keyword_function_t )( const Tuple &args, const Dict &kws );</pre> <p>That is, the methods take a Tuple or a Tuple and a Dict, and return an Object. The example below has an &in front of the name of the method; we found one compiler that needed this.</p> <h2><a name="h2_creating_extension_type">Creating a Python extension type</a></h2> <p>One of the great things about Python is the way you can create your own object types and have Python welcome them as first-class citizens. Unfortunately, part of the way you have to do this is not great. Key to the process is the creation of a Python "type object". All instances of this type must share a reference to this one unique type object. The type object itself has a multitude of "slots" into which the addresses of functions can be added in order to give the object the desired behavior. </p> <p>Creating extension objects is of course harder since you must specify how the object behaves and give it methods. This is shown in some detail in the example range.h and range.cxx, with the test routine rangetest.cxx, in directory Demo. If you have never created a Python extension before, you should read the Extension manual first and be very familiar with Python's "special class methods". Then what follows will make more sense.</p> <p>The basic idea is to inherit from PythonExtension templated on your self</p> <pre>class MyObject: public PythonExtension<MyObject> {...}</pre> <p>As a consequence: </p> <ul> <li>MyObject is a child of PyObject, so that a MyObject* is-a PyObject*. </li> <li>A static method <cite>check( PyObject * )</cite> is created in class MyObject. This function returns a boolean, testing whether or not the argument is in fact a pointer to an instance of MyObject.</li> <li>The user can connect methods of MyObject to Python so that they are methods on MyObject objects. Each such method has the signature:<br /> Object method_name( const Tuple &args ).</li> <li>The user can override virtual methods of PythonExtension in order to set behaviors.</li> <li>A method is created to handle the deletion of an instance if and when its reference count goes to zero. This method ensures the calling of the class destructor ~MyObject(), if any, and releases the memory( see below ).</li> <li>Both automatic and heap-based instances of MyObject can be created.</li> </ul> <h2><a name="h2_sample_pythonextension">Sample usage of PythonExtension</a></h2> <p>Here is a brief overview. You create a class that inherits from PythonExtension templated upon itself. You override various methods from PythonExtension to implement behaviors, such as getattr, sequence_item, etc. You can also add methods to the object that are usable from Python using a similar scheme as for module methods above. </p> <p>One of the consequences of inheriting from PythonExtension is that you are inheriting from PyObject itself. So your class is-a PyObject and instances of it can be passed to the Python C API. Note: this example uses the namespace feature of PyCXX.</p> <p>Hint: You can avoid needing to specify the Py:: prefix if you include the C++ statement <cite>using Py;</cite> at the top of your files.</p> <pre>class range: public Py::PythonExtension<range> { public: ... constructors, data, etc. ... methods not callable from Python // initializer, see below static void init_type(); // override functions from PythonExtension virtual Py::Object repr(); virtual Py::Object getattr( const char *name ); virtual int sequence_length(); virtual Py::Object sequence_item( int i ); virtual Py::Object sequence_concat( const Py::Object &j ); virtual Py::Object sequence_slice( int i, int j ); // define python methods of this object Py::Object amethod( const Py::Tuple &args ); Py::Object value( const Py::Tuple &args ); Py::Object assign( const Py::Tuple &args ); };</pre> <p> To initialize the type we provide a static method that we can call from some module's initializer. We set the name, doc string, and indicate which behaviors range objects support. Then we adds the methods.</p> <pre>void range::init_type() { behaviors().name( "range" ); behaviors().doc( "range objects: start, stop, step" ); behaviors().supportRepr(); behaviors().supportGetattr(); behaviors().supportSequenceType(); add_varargs_method( "amethod", &range::amethod, "demonstrate how to document amethod" ); add_varargs_method( "assign", &range::assign ); add_varargs_method( "value", &range::value ); behaviors().readyType(); }</pre> <p>Do not forget to add the call range::init_type() to some module's init function. You will want a method in some module that can create range objects, too.</p> <p>Your extension class T inherits PythonExtension<T>.</p> <table cellspacing="0" cellpadding="3px"> <caption>class PythonExtension<T></caption> <tr> <th>Type</th> <th>Name</th> <th>Comment</th> </tr> <tr> <td class="code">virtual</td> <td class="code">~PythonExtension<T>() </td> <td>Destructor</td> </tr> <tr> <td class="code">PyTypeObject* </td> <td class="code">type_object() const</td> <td>Returns the object type object.</td> </tr> <tr> <td class="code">int</td> <td class="code">check( PyObject *p )</td> <td>Is p a T?</td> </tr> <tr> <td colspan="3"><strong>Protected</strong></td> </tr> <tr> <td class="code">void</td> <td class="code">add_varargs_method( char *name, method_keyword_function_t method, char *documentation=""</td> <td>Add a method that takes arguments</td> </tr> <tr> <td class="code">void </td> <td class="code">add_keyword_method( char *name, method_keyword_function_t method, char *documentation=""</td> <td>Add a method that takes keywords</td> </tr> <tr> <td class="code">static PythonType&</td> <td class="code">behaviors()</td> <td>The type object</td> </tr> <tr> <td class="code">void</td> <td class="code">initialize()( protected, call from constructor )</td> <td>Initialize the module once all methods have been added. </td> </tr> </table> <p>As before the signatures for the methods are Object mymethod( const Tuple &args ) and Object mykeywordmethod( const Tuple &args, const Dict &keys ). In this case, the methods must be methods of T.</p> <p>To set the behaviors of the object you override some or all of these methods from PythonExtension<T>:</p> <pre>virtual int print( FILE *, int ); virtual Object getattr( const char * ); virtual int setattr( const char *, const Object &); virtual Object getattro( const Object &); virtual int setattro( const Object &, const Object &); virtual int compare( const Object &); virtual Object repr(); virtual Object str(); virtual long hash(); virtual Object call( const Object &, const Object &); // Sequence methods virtual int sequence_length(); virtual Object sequence_concat( const Object &); virtual Object sequence_repeat( int ); virtual Object sequence_item( int ); virtual Object sequence_slice( int, int ); virtual int sequence_ass_item( int, const Object &); virtual int sequence_ass_slice( int, int, const Object &); // Mapping virtual int mapping_length(); virtual Object mapping_subscript( const Object &); virtual int mapping_ass_subscript( const Object &, const Object &); // Number virtual int number_nonzero(); virtual Object number_negative(); virtual Object number_positive(); virtual Object number_absolute(); virtual Object number_invert(); virtual Object number_int(); virtual Object number_float(); virtual Object number_long(); virtual Object number_oct(); virtual Object number_hex(); virtual Object number_add( const Object &); virtual Object number_subtract( const Object &); virtual Object number_multiply( const Object &); virtual Object number_divide( const Object &); virtual Object number_remainder( const Object &); virtual Object number_divmod( const Object &); virtual Object number_lshift( const Object &); virtual Object number_rshift( const Object &); virtual Object number_and( const Object &); virtual Object number_xor( const Object &); virtual Object number_or( const Object &); virtual Object number_power( const Object &, const Object &); // Buffer virtual int buffer_getreadbuffer( int, void** ); virtual int buffer_getwritebuffer( int, void** ); virtual int buffer_getsegcount( int* );</pre> <p>Note that dealloc is not one of the functions you can override. That is what your destructor is for. As noted below, dealloc behavior is provided for you by PythonExtension.</p> <h2><a name="h2_type_initialization">Type initialization</a></h2> <p>To initialize your type, supply a static public member function that can be called from the extension module. In that function, obtain the PythonType object by calling behaviors() and apply appropriate "support" methods from PythonType to turn on the support for that behavior or set of behaviors.</p> <pre>void supportPrint( void ); void supportGetattr( void ); void supportSetattr( void ); void supportGetattro( void ); void supportSetattro( void ); void supportCompare( void ); void supportRepr( void ); void supportStr( void ); void supportHash( void ); void supportCall( void ); void supportSequenceType( bool support_assignment=true, bool support_inplace=false, bool support_contains=false ); void supportMappingType( bool support_assignment=true ); void supportNumberType( void ); void supportBufferType( void );</pre> <p>Then call add_varargs_method or add_keyword_method to add any methods desired to the object.</p> <h2><a name="h2_memory_management">Notes on memory management and extension objects</a></h2> <p>Normal Python objects exist only on the heap. That is unfortunate, as object creation and destruction can be relatively expensive. Class PythonExtension allows creation of both local and heap-based objects.</p> <p>If an extension object is created using operator new, as in:</p> <pre>range* my_r_ref = new range( 1, 20, 3 )</pre> <p>then the entity my_r_ref can be thought of as "owning" the reference created in the new object. Thus, the object will never have a reference count of zero. If the creator wishes to delete this object, they should either make sure the reference count is 1 and then do delete my_r_ref, or decrement the reference with Py_DECREF( my_r_ref ).</p> <p>Should my_r_ref give up ownership by being used in an Object constructor, all will still be well. When the Object goes out of scope its destructor will be called, and that will decrement the reference count, which in turn will trigger the special dealloc routine that calls the destructor and deletes the pointer.</p> <p>If the object is created with automatic scope, as in:</p> <pre>range my_r( 1, 20, 3 )</pre> <p>then my_r can be thought of as owning the reference, and when my_r goes out of scope the object will be destroyed. Of course, care must be taken not to have kept any permanent reference to this object. Fortunately, in the case of an exception, the C++ exception facility will call the destructor of my_r. Naturally, care must be taken not to end up with a dangling reference, but such objects can be created and destroyed more efficiently than heap-based PyObjects.</p> </body> </html>