[Numpy-discussion] Options for wrapping C and C++ code for use with Numeric

Stefan van der Walt stefan at sun.ac.za
Thu Nov 3 23:38:21 CST 2005


Hi Chris

On Thu, Nov 03, 2005 at 03:42:51PM -0800, Chris Barker wrote:
> Bruce Southey wrote:
> >Hi,
> >I found SWIG extremely to use but it only exposes a function to Python but
> >not to numpy. Thus it is very slow for matrix functions. So if you want
> >speed then you will have to deal with the APIs.
> 
> Yes, but can't I deal with them in writing typemaps, and then let SWIG 
> do the rest of the work? I think I've seen some examples like this 
> somewhere, but it's been a while and I need to go digging more.

I use SWIG and Blitz++ this way, and it works well.  I modified
Fernando's typemap to work with templates.  See attached (does
this need to be modified for Numeric3?).

It is easy to create a Blitz matrix from a Numeric Array without
copying data.  Unfortunately, Blitz jealously guards its data
(restricted pointers), so that it is not so easy to do the conversion
in the other direction.  If anyone knows an answer to this problem,
I'd be glad to hear it.

Stéfan
-------------- next part --------------
// -*- C++ -*-

%{
#include <blitz/array.h>
#include <blitz/tinyvec.h>
#include <Numeric/arrayobject.h>
%}

namespace blitz {

    template <class T, int N> class Array {

	%typemap(in) Array<T,N> & (Array<T,N> M) {
	    int T_size = sizeof(T);
	    
	    blitz::TinyVector<int,N> shape(0);
	    blitz::TinyVector<int,N> strides(0);
	    
	    int *arr_dimensions = ((PyArrayObject*)$input)->dimensions;
	    int *arr_strides = ((PyArrayObject*)$input)->strides;
	    
	    for (int i = 0; i < N; i++) {
		shape[i]   = arr_dimensions[i];
		strides[i] = arr_strides[i]/T_size;
	    }
	    
	    M.reference(blitz::Array<T,N>((T*) ((PyArrayObject*)$input)->data,
					  shape, strides, blitz::neverDeleteData));
	    
	    $1 = &M;
	}

    };
}

%template(matrix1d) blitz::Array<double, 1>;
%template(matrix2d) blitz::Array<double, 2>;
%template(matrix3d) blitz::Array<double, 3>;

%template(matrix1f) blitz::Array<float, 1>;
%template(matrix2f) blitz::Array<float, 2>;
%template(matrix3f) blitz::Array<float, 3>;


More information about the Numpy-discussion mailing list