[C++-sig] Re: registering simple conversions from/to python

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Wed May 28 18:08:54 CEST 2003


--- Brett Calcott <brett.calcott at paradise.net.nz> wrote:
> Wow! I was off on some wild goose chase making things complicated,
> thinking I had to write custom converters..

Hey, hey, hey... not so fast!
The add_property approach is cute but doesn't scale. Soon you will find that
you want to add, multiply, divide, etc. using operator overloading and that you
need a whole bunch of other member functions. Without the automatic from/to
Python tuple conversions you will have to write funky wrappers for each of your
overloaded operators or member functions. The custom converters are very
efficient in consolidating this clutter in one central place.

Besides, I forgot to point out this little helper at the bottom of
container_conversions.h:

#include <somewhere/container_conversions.h>
scitbx::boost_python::container_conversions::tuple_mapping_fixed_size<
  boost::array<double, 2> >();

One include and one line of code (in one of your module initialization
functions), that's all you need. In terms of code-to-write it beats the
add_property approach by an order of magnitude. Now move away from artificially
chopping your coordinate object into pieces (.x, .y) only to put it back
together later (.xy) and everything will magically fall into place (untested):

class C
{
  boost::array<double, 2> xy;
  
  C() {}
  C(boost::array<double, 2> const& xy_) : xy(xy_) {}

  boost::array<double, 2>
  operator+(boost::array<double, 2> const& other)
  {
    boost::array<double, 2> result;
    result[0] = xy[0] + other[0];
    result[1] = xy[1] + other[1];
    return result;
  }

  //etc.
};

class_<C>("C")
  .def(init<boost::array<double, 2> >())
  .def(self + self)
;

Ralf


__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com




More information about the Cplusplus-sig mailing list