[Numpy-discussion] How to call methods from a class with custom matrices parameters with numpy arrays ?

David Cournapeau cournape@gmail....
Thu Apr 19 11:03:00 CDT 2007

On 4/19/07, Matthieu Brucher <matthieu.brucher@gmail.com> wrote:
> > I forgot you are using C++.
> Yes, all my code is in C++, and in fact the code I use in Python should be
> object-oriented as well, that's why it is not that easy to define how I'm
> going to do this...
Doing the wrapping in an object oriented way is difficult, and maybe
not that useful. This does not prevent the API exposed to python to be
OO, of course.
> > Using C++ with ctypes makes the wrapping
> > more difficult, I think, specially since you are using templates: you
> > would have to write a C wrapper around your classes, and then using
> > ctypes on the wrapper (there may be better ways, but I don't see an
> > obvious one). Basically, using ctypes is like using code from a
> > dynamically loaded library (ala VST :) ).
> That works great for C then, not that well for C++...
Well, this is an inherent problem of C++ when you try to use it from
other languages, but let's not start this (again :) ),
> Yes, but even with SWIG, I think I'll have to write wrapper in C or in SWIG
> to transform one array in my matrix and vice versa. Well, that should be a
> great example for my book ;)
> > I have attached a simplistic example which show how to wrap some
> functions.
> Many thanks, it is simple, I only have to provide the wrappers :| and I have
> to do something with the class instance :| I'll think a little bit about how
> to do this properly and efficiently
The example shows basic wrapping, and some facilities provided by
numpy to help. Again, ctype is pretty efficient as long as you do not
need to do convertion. If you call it thousand of times, it will be
slow, but this is more or less inherent to python (function calls are
nowhere near as fast as in a compiled language, at least for now).

SWIG may be better in your case because it is aware of C++ classes,
and is *compiling* an extension, whereas ctypes does not compile
anything. This means that you do not have to care about binary
interfaces problemes between foreign object codes. SWIG parses a prett
good deal of C++, and is aware of classes (template is another matter,
obviously). numpy sources contain swig code to process automatically
numpy arrays (that is convert C representation of a numpy array to a
simple C array and vice et versa), if I remember correctly.

There is also boost.python, but I don't know if its situation towards
numpy array has changed (eg there was some code lying around to
represent numpy arrays in C++).

If I were you, and if there are only a few classes and a few member
functions, I would try the C wrapper called from python first.


More information about the Numpy-discussion mailing list