[C++-sig] getting shape of numpy array

Michele De Stefano micdestefano at gmail.com
Tue Nov 10 14:35:13 CET 2009


Hello Nathan.

Find my answers below.

2009/11/10 Nathan Huesken <boost-python at lonely-star.org>:
> Hi,
>
> I am trying to interaface a numpy array using boost::python::numeric::array.
>
> void function(numeric::array& a)
> {
>        tuple shape=extract<tuple>(a.getshape());
>        double x;
>        int i,j;
>        for(i=0;i<shape[0];++i)
>                for(j=0;j<shape[1];++j)
>                        x=extract<double>(a[make_tuple(i,j)]);
> }
>
> Now I had to add
> numeric::array::set_module_and_type("numpy", "ndarray");
>
> to the module, hope that was correct.
>
> When I call this function in python, I get:
> AttributeError: 'numpy.ndarray' object has no attribute 'getshape'

The error comes out because, actually, numpy.ndarray has no getshape method.

>
> What is the correct way to do it?
>

Within your function, declare

const tuple	&shape = extract<tuple>(in.attr("shape"));


I suggest you to have a look also at my open source library (mds-utils):

http://code.google.com/p/mds-utils/

I've written some from/to Python converters that are able to convert a
Python sequence directly into a Boost uBLAS vector or matrix.
If you download the software, you can build the doxygen documentation
(follow the instructions) and you will find an example for each C++
class or function.

In other words, using my library, you could write your function as:

void function(const boost::numeric::ublas::matrix<double>& m) {
...
}

and export it to Python and pass, from Python, a Numpy 2D array.

Have a look at mds-utils and at its usage examples.

Bye,
Michele

> Thanks!
> Nathan
> --
> _______________________________________________
> Cplusplus-sig mailing list
> Cplusplus-sig at python.org
> http://mail.python.org/mailman/listinfo/cplusplus-sig
>



-- 
Michele De Stefano
http://www.linkedin.com/in/micdestefano
http://code.google.com/p/mds-utils
http://xoomer.virgilio.it/michele_de_stefano


More information about the Cplusplus-sig mailing list