User guide
NumPy User Guide, Release 1.9.0
Boost Python
Boost is a repository of C++ libraries and Boost.Python is one of those libraries which provides a concise interface
for binding C++ classes and functions to Python. The amazing part of the Boost.Python approach is that it works
entirely in pure C++ without introducing a new syntax. Many users of C++ report that Boost.Python makes it possible
to combine the best of both worlds in a seamless fashion. I have not used Boost.Python because I am not a big user of
C++ and using Boost to wrap simple C-subroutines is usually over-kill. It’s primary purpose is to make C++ classes
available in Python. So, if you have a set of C++ classes that need to be integrated cleanly into Python, consider
learning about and using Boost.Python.
Instant
This is a relatively new package (called pyinstant at sourceforge) that builds on top of SWIG to make it easy to inline
C and C++ code in Python very much like weave. However, Instant builds extension modules on the fly with specific
module names and specific method names. In this repsect it is more more like f2py in its behavior. The extension
modules are built on-the fly (as long as the SWIG is installed). They can then be imported. Here is an example of
using Instant with NumPy arrays (adapted from the test2 included in the Instant distribution):
code="""
PyObject
*
add(PyObject
*
a_, PyObject
*
b_){
/
*
various checks
*
/
PyArrayObject
*
a=(PyArrayObject
*
) a_;
PyArrayObject
*
b=(PyArrayObject
*
) b_;
int n = a->dimensions[0];
int dims[1];
dims[0] = n;
PyArrayObject
*
ret;
ret = (PyArrayObject
*
) PyArray_FromDims(1, dims, NPY_DOUBLE);
int i;
char
*
aj=a->data;
char
*
bj=b->data;
double
*
retj = (double
*
)ret->data;
for (i=0; i < n; i++) {
*
retj++ =
*
((double
*
)aj) +
*
((double
*
)bj);
aj += a->strides[0];
bj += b->strides[0];
}
return (PyObject
*
)ret;
}
"""
import Instant, numpy
ext = Instant.Instant()
ext.create_extension(code=s, headers=["numpy/arrayobject.h"],
include_dirs=[numpy.get_include()],
init_code=’import_array();’, module="test2b_ext")
import test2b_ext
a = numpy.arange(1000)
b = numpy.arange(1000)
d = test2b_ext.add(a,b)
Except perhaps for the dependence on SWIG, Instant is a straightforward utility for writing extension modules.
5.2. Using Python as glue 79