[C++-sig] [Boost.Python v3] Conversions and Registries

Jim Bosch talljimbo at gmail.com
Wed Oct 5 15:42:58 CEST 2011


On 10/05/2011 09:26 AM, Stefan Seefeld wrote:
> On 10/05/2011 09:18 AM, Jim Bosch wrote:
>>
>> I have one (perhaps unusual) use case that's extremely important for
>> me: I have a templated matrix/vector/array class, and I want to define
>> converters between those types and numpy that work with any
>> combination of template parameters.  I can do that with compile-time
>> converters, and after including the header everything just works.
>> With runtime conversions, I have to explicitly declare all the
>> template parameter combinations I intend to use.
>
> Jim,
>
> I may be a little slow here, but I still don't see the issue. You need
> to export your classes to Python one at a time anyhow, i.e. not as a
> template, letting the Python runtime figure out all valid template
> argument permutations. So why can't the converter definitions simply be
> bound to those type definitions ?
>

The key point is that I'm not exporting these with "class_"; I define 
converters that go directly to and from numpy.ndarray.  So if I define 
template-based converters for my class ("ndarray::Array<T,N,C>"), a 
function that takes one as an argument:

void fillArray(ndarray::Array<double,2,1> array);

...can be wrapped to take a numpy.ndarray as an argument, just by doing:

#include "array-from-python.hpp"
...
bp::def("fillArray", &fillArray);

Without template converters, I also have to add something like:

register_array_from_python< ndarray::Array<double,2,1> >();

(where register_array_from_python is some custom runtime converter I'd 
have written) and repeat that for every instantiation of ndarray::Array 
I use.  This involves looking through all my code, finding all the 
combinations of template parameters I use, and registering each one 
exactly once across all modules.  That would get better with some sort 
of multi-module registry support, but I don't think I should have to 
declare the converters for each set of template parameters at all; it's 
better just to write a single compile-time converter.

Jim


More information about the Cplusplus-sig mailing list