[C++-sig] more examples of automatic type conversion

Albert Strasheim fullung at gmail.com
Thu May 3 10:33:51 CEST 2007

On Wed, 02 May 2007, Roman Yakovenko wrote:

> On 5/2/07, Eric Jonas <jonas at mit.edu> wrote:
> > Hello! I'm using boost::python to try and interface numpy (that is, the
> > newest numpy, not numeric or numarray) ndarray objects to my code which
> > depends on boost::multi_array. I've written functions that take a
> > pyobject* and return a multiarray and vice versa. Now I'm at the point
> > of interfacing my c++ classes (which take multi_array references in
> > their constructors). Rather than adulterating their interfaces by adding
> > additional constructors with PyObject* arguments, is there some way of
> > telling boost::python to use my conversion functions automatically?
> http://www.language-binding.net/pyplusplus/troubleshooting_guide/automatic_conversion/automatic_conversion.html
> Let me know if this helped you.

As luck would have it, I also started playing with this idea yesterday 
and I found the above-mentioned page to help me along. I'm mostly 
interested in wrapping an interface written in terms of uBLAS vectors, 
matrices and vector-of-vectors.

One issue I've run into with uBLAS is that there doesn't seem to be an 
array adaptor (the A in matrix<T, L, A>) that can be used to wrap 
existing memory without copying at some point. Writing an array adaptor 
like this shouldn't be too hard though.

Another issue is that you have to be very careful with the 
vector/matrix type you use, since converting a NumPy array to
matrix<T, L, adapter_that_doesnt_copy<T> > and passing that to a 
function that expects matrix<T> doesn't work (strange crashes, probably 
due to the slight difference in size between the objects, due to the 
different array adaptors being used).

Anyway, I've more or less got pass-by-value and return-by-value working 
using Roman's example, but I can't quite figure out how to make 
Boost.Python convert pointer and reference arguments or return values 
into PyObject*'s using the same scheme. Should this just work if I have 
my automatic conversion set up correctly, or is there additional magic 
that needs to be added? Again, it would be *very* useful if copying 
could be avoided here.

Any hints would be appreciated.



More information about the Cplusplus-sig mailing list