[Numpy-discussion] (newbie) How can I use NumPy to wrap my C++ class with 2-dimensional arrays?

Christopher Barker Chris.Barker@noaa....
Mon Aug 3 18:17:10 CDT 2009

Raymond de Vries wrote:

> Oops, I guess I didn't express myself clearly enough: I have used plain 
> Python c-api (in my case a list of lists for my 2-dimensional arrays) 
> for my typemaps. Sorry for the unclearness. Actually because NumPy is 
> not my cup of tea... 

Well, for almost any purpose, numpy arrays are a better fit for a 2-d 
array of numbers than a list of lists, so I'm not sure what kind of tea 
you like ;-)

> Especially because Matthieu suggested that I should 
> convert my data into a contiguous array.

a Python list can't share a pointer with your C++ data type anyway, so 
you'll have to copy anyway -- why not make a contiguous array?

If you need a "ragged" array, then it's a different story, but a list of 
numpy arrays may be a better fit.

> So no matter what I use, either swig, cython, or.. I still have the 
> NumPy issue.

True, it's probably best to decide what sort of representation you want 
in Python, then decide how to build your wrappers. If you have a big 2-d 
array in C++, numpy is the obvious choice.

Another choice is a wrapper around your C++ class -- don't convert to a 
python type at all. Depending on what you need to do, it may be OK to 
lost a lot of functionality numpy give you.

This is how the SWIG C++ vector wrappers work, for instance.


Christopher Barker, Ph.D.

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception


More information about the NumPy-Discussion mailing list