[Numpy-discussion] A C++ library and the new array interface: the best approach?

Simon Anders simon.anders at uibk.ac.at
Tue Jul 4 05:03:07 CDT 2006

Hi Fernando,

Fernando Perez schrieb:
> So I'd like to know if SWIG is really the best way out in this particular case 
> (and any advice on taking advantage of the array interface via SWIG would be 
> appreciated), or if ctypes or pyrex could be used here.  I'm quite happy using 
> pyrex in other contexts, but I know it doesn't directly support C++.  However, 
> since I have access to all the code, perhaps a pure C layer could be used to 
> bridge the C++/pyrex gap.  Or given the recent praise for ctypes, perhaps that 
> can be an option?

I'm not so sure either, whether SWIG is the way to go. If, however, you
decide to give it a try, you could try a little tool I am currently
working on. It is basically a SWIG typemap definition which allows for
easy use of numpy arrays from C++.

In brief, I have defined a C++ template class around numpy's own
PyArrayObject structure which allows for convenient access of the array
data using C++-like techniques and takes care of type checking and the
like. As it adds only non-virtual methods and no fields, the objects are
memory-wise identical to numpy's own array structure and can hence be
passed between C++ and Python without any copying of data or metadata.

The original idea behind was a bit the opposite of your problem. I had
program for a numerical computation, written in Python, and wanted to
rewrite the most performance-critical parts in C++. With my SWIG
typemap, I can now write the C++ part using my template class and wrap
it such that these objects appear to Python as numpy array objects.

For your problem, it might be a way to write a kind of casting functions
that takes one of your tensor objects and transforms it into my numpy
objects. This should be possible with only copying metadata (i.e. fields
containing dimensions and the like) but with leaving the actual data in

My stuff is still a bit work in progress, and so I don't want to post it
here yet, but it may help you to not have to start from scratch, as  the
typemap code would help you to get started and might be easy to adjust
to your needs.

So, if you are interested, send me a mail, and I would appreciate any
comments from you on how to make my tool into seomthing really reusable.


| Simon Anders, Dipl. Phys.
| Institut fuer Theoretische Physik, Universitaet Innsbruck, Austria
| Tel. +43-512-507-6207, Fax -2919
| preferred (permanent) e-mail: sanders at fs.tum.de

More information about the Numpy-discussion mailing list