[Numpy-discussion] Options for wrapping C and C++ code for use with Numeric
Travis Oliphant
oliphant at ee.byu.edu
Thu Nov 3 23:44:23 CST 2005
Stefan van der Walt wrote:
>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?).
>
>
>
Only a little bit. I'll mark the changes
>StÃ©fan
>
>
>------------------------------------------------------------------------
>
>// -*- C++ -*-
>
>%{
>#include <blitz/array.h>
>#include <blitz/tinyvec.h>
>#include <Numeric/arrayobject.h>
>
>
#include "scipy/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>;
>
>
On 32-bit platforms, this code would work fine.
On 64-bit platforms, you would need to change at least the
arr_dimensions and arr_strides arrays to be intp (typedef to an integer
the size of a pointer on the platform).
-Travis
More information about the Numpy-discussion
mailing list