[SciPy-user] weave and access to Numeric arrays

Fernando Perez fperez at pizero.colorado.edu
Mon Jul 22 20:19:25 CDT 2002

On Mon, 22 Jul 2002, eric jones wrote:

> # f.py
> from scipy import weave
> def sum(x):
>     code = """
>            float result=0;
>            for (i = 0; i < _Nx; i++)
>                result += x_data[i];
>            return_val = Py::new_reference_to(Py::Float(result));    
>            """
>     return weave.inline(code,['x'])        
> from scipy import *
> x = ones(10,typecode=Float32)
> print sum(x)    
> C:\home\eric\STSci\chaco>python f.py
> 10.0

Wow, Eric, hold it! How does that code work? I had to test it on my machine 
before I actually believed it! A few questions:

1. Why don't you need to declare i? I was always declaring my counters 
everywhere. What are the rules for what gets magically created by weave?  I 
wasn't aware of this.

2. Who creates x_data and _Nx? How can I know which magical variables exist, 
and what they correspond to in the Numeric C API? I've read what a numeric 
array looks like in C, so if there's a way of knowing how the various fields 
of that structure are visible in the weave code, that would be great. Esp. for 
multi-dimensional arrays are there various _N's?

If this is documented somewhere, feel free to tell me to RTFM. But I've read 
in the past the weave docs and certainly all of this is news to me. I have 
that page of weave examples I told you about and I could include and document 
some of this for public consumption once I understand it. I read all the 
examples in weave/examples, and I see some of this _N stuff but zero comments 
about it.

I'd greatly appreciate it if you give me a couple of pointers on this. I'll 
pay you back by adding the newly gained wisdom to my weave examples page and 
reposting it here on the list for other's benefit.

Thanks a lot,


ps. And yes, what you gave me is exactly what I wanted. I just now want to 
really understand how it ticks for other more complicated cases I need to deal 

More information about the SciPy-user mailing list