![]()
|
Writing Python Extensions in C++Paul F. Dubois, dubois1@llnl.gov Barry Scott PyCXX is designed to make it easier to extend Python with C++ 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:
Download and InstallationDownload PyCXX from http://sourceforge.net/projects/cxx/. The distribution layout is:
To use PyCXX you use its include files and add its source routines to your module. Installation:
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. Use of namespacesAll PyCXX assets are in namespace "Py". You need to include the Py:: prefix when referring to them, or include the statement: using namespace Py; Wrappers for standard objects: CXX_Objects.hHeader file CXX_Objects.h requires adding file Src/cxxsupport.cxx to your module sources. CXX_Objects 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: d = {} d["a"] = 1 d["b"] = 2 alist = d.keys() print alist Can be written in C++: Dict d; List alist; d["a"] = Int(1); d["b"] = Int(2); alist = d.keys(); std::cout << alist << std::endl; You can optionally use the CXX/Extensions.hxx facility described later to define Python extension modules and extension objects. We avoid programming with Python object pointersThe essential idea is that we avoid, as much as possible, programming with pointers to Python objects, that is, variables of type PyObject*. 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. For example, consider the case in which we wish to write a method, taking a single integer argument, that will create a Python dict and insert into it that the integer plus one under the key value. In C we might do that as follows: static PyObject* mymodule_addvalue (PyObject* self, 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; } 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 (Int, Dict, Tuple) are from CXX/Objects.hxx. static PyObject* mymodule_addvalue (PyObject* self, PyObject* pargs) { try { Tuple args(pargs); args.verify_length(1); Dict d; Int k = args[0]; d["value"] = k + 1; return new_reference_to(d); } catch (const PyException&) { return NULL; } } 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. Note that the creation of the Int k got the first argument and verified that it is an Int. 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 even more simply: Object addvalue (Object & self, const Tuple & args) { args.verify_length(1); Dict d; Int k = args[0]; d["value"] = k + 1; return d; } The basic concept is to wrap Python pointersThe basic concept of CXX/Objects.hxx is to create a wrapper around each PyObject * 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. Each Object contains a PyObject * to which it owns a reference. When an Object 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. 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. Class Object represents the most general kind of Python object. The rest of the classes that represent Python objects inherit from it. Object Type Int Float Long Complex Char Sequence -> SeqBase<T> String Tuple List Mapping -> MapBase<T> Dict Callable Module There are several constructors for each of these classes. For example, you can create an Int from an integer as in Int s(3) However, you can also create an instance of one of these classes using any PyObject* or another Object. If the corresponding Python object does not actually have the type desired, an exception is thrown. This is accomplished as follows. Class Object defines a virtual function accepts: virtual bool accepts(PyObject* p) The base class version of accepts returns true for any pointer p except 0. This means we can create an Object using any PyObject *, or from any other Object. However, if we attempt to create an Int from a PyObject *, the overridding version of accepts in class Int will only accept pointers that correspond to Python ints. Therefore if we have a Tuple t and we wish to get the first element and be sure it is an Int, we do Int first_element = t[0] This will not only accomplish the goal of extracting the first element of the Tuple t, but it will ensure that the result is an Int. If not, an exception is thrown. The exception mechanism is discussed later. Class ObjectClass Object serves as the base class for the other classes. Its default constructor constructs a Py_None, the unique object of Python type None. The interface to Object 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. There is no method corresponding to PyObject_SetItem with an arbitrary Python object as a key. Instead, create an instance of a more specific child of Object and use the appropriate facilities. The comparison operators use the Python comparison function to compare values. The method is is available to test for absolute identity. A conversion to standard library string type std::string is supplied using method as_string. Stream output of PyCXX Object instances uses this conversion, which in turn uses the Python object's str() representation. All the numeric operators are defined on all possible combinations of Object, long, and double. These use the corresponding Python operators, and should the operation fail for some reason, an exception is thrown. Dealing with pointers returned by the Python C APIOften, PyObject * 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 owned or unowned reference. Unowned references are unusual but there are some cases where unowned references are returned. Usually, Object and its children acquire a new reference when constructed from a PyObject *. This is usually not the right behavior if the reference comes from one of the Python C API calls. If p is an owned reference, you can add the boolean true as an extra argument in the creation routine, Object(p, true), or use the function asObject(p) which returns an Object created using the owned reference. For example, the routine PyString_FromString returns an owned reference to a Python string object. You could write: Object w = asObject( PyString_FromString("my string") ); or using the constructor, Object w( PyString_FromString("my string"), true ); In fact, you would never do this, since PyCXX has a class String and you can just say: String w( "my string" ); Indeed, since most of the Python C API is similarly embodied in Object and its descendents, you probably will not use asObject all that often. Table 1: Class Object
The Basic TypesCorresponding 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. Class TypeClass Type corresponds to Python type objects. There is no default constructor. Table 2: class Type
Class IntClass Int, derived publically from Object, corresponds to Python ints. Note that the latter correspond to C long ints. Class Int has an implicit user-defined conversion to long int. All constructors, on the other hand, are explicit. The default constructor creates a Python int zero. Table 3: class Int
Class LongClass Long, derived publically from Object, corresponds to Python type long. In Python, a long is an integer type of unlimited size, and is usually used for applications such as cryptography, not as a normal integer. 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. Table 4: Class Long
Class FloatClass Float corresponds to Python floats, which in turn correspond to C double. The default constructor produces the Python float 0.0. Table 5: Class Float
SequencesPyCXX 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. 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. 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. For convenience, the word Sequence is a typedef of SeqBase<Object>. General sequencesSuppose 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: static PyObject* my_module_seqlen (PyObject *self, 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(Int(s.length())); } catch(const PyException&) { return Py_Null; } } 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. SubscriptingWhen 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. In normal use, you are not supposed to notice this magic going on behind your back. You write: Object t; Sequence s; s[2] = t + s[1] 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. 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. IteratorsEach 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.h if necessary. The purpose of most of this interface is to satisfy requirements of the STL. The SeqBase<T> InterfaceSeqBase<T> inherits from Object.
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. Classes Char and StringPython 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. The user interface for Char is limited. Unlike String, for example, it is not a sequence. The Char interfaceChar inherits from Object.
The String InterfaceString inherits from SeqBase<Char>.
Class TupleClass 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. 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. Example: create a Tuple containing (1, 2, 4) Tuple t(3) t[0] = Int(1) t[1] = Int(2) t[2] = Int(4) Example: create a Tuple from a list: Dict d ... Tuple t(d.keys()) The Tuple InterfaceTuple inherits from Sequence.. Special run-time checks prevent modification if the reference count is greater than one.
Class ListClass List represents a Python list, and the methods available faithfully reproduce the Python API for lists. A List is a Sequence. The List InterfaceList inherits from Sequence.
MappingsA 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. For convenience, Mapping is a typedef for MapBase<Object>. The MapBase<T> interfaceMapBase<T> inherits from Object. T should be chosen to reflect the kind of element returned by the mapping.
Class DictClass Dict represents Python dictionarys. A Dict is a Mapping. Assignment to subscripts can be used to set the components. Dict d d["Paul Dubois"] = "(925)-422-5426" Interface for Class DictDict inherits from MapBase<Object>.
Other classes and facilities.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. Interface to class Callable
Interface to class Module
Numeric interfaceUnary 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. The signature for coerce is: inline std::pair<Object,Object> coerce(const Object& a, const Object& b) Unlike the C API function, this simply returns the pair after coercion. Stream I/OAny 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&). ExceptionsThe Python exception facility and the C++ exception facility can be merged via the use of try/catch blocks in the bodies of extension objects and module functions. Class Exception and its childrenA set of classes is provided. Each is derived from class Exception, and represents a particular sort of Python exception, such as IndexError, RuntimeError, ValueError. Each of them (other than Exception) has a constructor which takes an explanatory string as an argument, and is used in a throw statement such as: throw IndexError("Index too large in MyObject access."); If in using a routine from the Python API, you discover that it has returned a NULL indicating an error, then Python has already set the error message. In that case you merely throw Exception. List of ExceptionsThe exception hierarchy mirrors the Python exception hierarchy. The concrete exception classes are shown here.
Using Exceptions in extension methodsThe 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. 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. Catching Exceptions from the Python API or PyCXX.When writing an extension module method, you can use the following boilerplate. Any exceptions caused by the Python API or PyCXX itself will be converted into a Python exception. Note that Exception is the most general of the exceptions listed above, and therefore this one catch clause will serve to catch all of them. You may wish to catch other exceptions, not in the Exception family, in the same way. If so, you need to make sure you set the error in Python before returning. static PyObject * some_module_method(PyObject* self, PyObject* args) { Tuple a(args); // we know args is a Tuple try { ...calculate something from a... return ...something, usually of the form new_reference_to(some Object); } catch(const Exception&) { //Exception caught, passing it on to Python return Null (); } } How to clear an ExceptionIf you anticipate that an Exception may be thrown and wish to recover from it, change the catch phrase to set a reference to an Exception, and use the method clear() from class Exception to clear it.: catch(Exception& e) { e.clear(); ...now decide what to do about it... } Extension FacilitiesCXX/Extensions.hxx provides facilities for:
These facilities use CXX/Objects.hxx and its support file cxxsupport.cxx. If you use CXX/Extensions.hxx you must also include source files cxxextensions.c and cxx_extensions.cxx Creating an Python extension moduleThe 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:
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): 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) { ... } }; To initialize the extension, you just instantiate one static instance (static so it does not destroy itself!): void initexample() { static example_module* example = new example_module; } 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: 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; } class ExtensionModule contains methods to return itself as a Module object, or to return its dictionary. Interface to class ExtensionModule
The signatures above are: typedef Object (T::*method_varargs_function_t)( const Tuple &args ); typedef Object (T::*method_keyword_function_t)( const Tuple &args, const Dict &kws ); 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. Creating a Python extension typeOne 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. 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. The basic idea is to inherit from PythonExtension templated on your self class MyObject: public PythonExtension<MyObject> {...} As a consequence:
Sample usage of PythonExtensionHere 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. 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. Hint: You can avoid needing to specify the Py:: prefix if you include the C++ statement using Py; at the top of your files. 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); }; 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. 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); } 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. Interface to PythonExtension <T>Your extension class T inherits PythonExtension<T>.
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. To set the behaviors of the object you override some or all of these methods from PythonExtension<T>: 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* ); 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. Type initializationTo 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. 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(void); void supportMappingType(void); void supportNumberType(void); void supportBufferType(void); Then call add_varargs_method or add_keyword_method to add any methods desired to the object. Notes on memory management and extension objectsNormal 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. If an extension object is created using operator new, as in: range* my_r_ref = new range(1, 20, 3) 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). 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. If the object is created with automatic scope, as in: range my_r(1, 20, 3) 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. Putting it all togetherThe Demo directory of the distribution contains an extensive example of how to use many of the facilities in PyCXX. It also serves as a test routine. This test is not completely exhaustive but does excercise much of the facility. AcknowledgmentThank 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 |