[Numpy-discussion] blitz++ and numarray

Fernando Perez Fernando.Perez at colorado.edu
Mon Mar 29 12:26:48 CST 2004


Faheem Mitha wrote:
> Hi,
> 
> I'm considering the use of the Blitz++ C++ library
> (http://www.oonumerics.org/blitz/) along with numarray/Numeric. I want
> to pass an array down to C++ and then manipulate it using Blitz++.

[snip]

> Also, weave.blitz() from SciPy looks relevant/useful, but this
> automatically generates its own C++ code, and I'd prefer to write my
> own.

The following should be enough to get you started:

#include "Python.h"
#include "Numeric/arrayobject.h"
#include "blitz/array.h"

using namespace std;
using namespace blitz;

// Convert a Numpy array to a blitz one, using the original's data (no copy)
template<class T, int N>
static Array<T,N> py_to_blitz(PyArrayObject* arr_obj)
{
     int T_size = sizeof(T);
     TinyVector<int,N> shape(0);
     TinyVector<int,N> strides(0);
     int *arr_dimensions = arr_obj->dimensions;
     int *arr_strides = arr_obj->strides;

     for (int i=0;i<N;++i) {
         shape[i]   = arr_dimensions[i];
         strides[i] = arr_strides[i]/T_size;
     }
     return Array<T,N>((T*) arr_obj->data,shape,strides,neverDeleteData);
}

This is what I use for exactly the problem you are describing, and this code 
was pretty much lifted, with minor changes, from weave's auto-generated C++. 
What I do, to sidestep the memory management problems, is let python allocate 
all my Numeric arrays (using zeros() if I have no data).  I then use those 
inside my C++ code as blitz++ arrays via the above snippet.  Any changes made 
by the C++ code are automatically reflected in the Numeric arary, since the 
blitz object is using the Numeric data area.

I hope this helps.  Let me know if you need more help, I can mail you complete 
example code.

Cheers,

f





More information about the Numpy-discussion mailing list