[C++-sig] wrapping a custom C++ iterator

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Thu Sep 12 16:24:41 CEST 2002


I have just wrapped my first custom C++ iterator with Boost.Python V2.
The C++ interface is minimal, there is just a default constructor and
a member function next(). In C++, end of iteration is determined by
inspecting the state of the result of next().
Attached is my code for the Python bindings. I feel quite confident
about my implementation of the binding for next(), but I am a bit
uncertain about the __iter__ hook:

1.
    static w_t& iter(w_t& o) { return o; }

2.
        .def("__iter__", iter, return_internal_reference<>())

This works, but is it the right approach?

Thanks!
        Ralf


  struct space_group_symbol_iterator_wrappers
  {
    typedef space_group_symbol_iterator w_t;

    static space_group_symbols
    next(w_t& o)
    {
      space_group_symbols result = o.next();
      if (result.sg_number() == 0) {
        PyErr_SetString(PyExc_StopIteration, "At end of table.");
        boost::python::throw_error_already_set();
      }
      return result;
    }

    static w_t& iter(w_t& o) { return o; }

    static void
    wrap()
    {
      using namespace boost::python;
      class_<w_t>("space_group_symbol_iterator",
        args<>())
        .def("next", next)
        .def("__iter__", iter, return_internal_reference<>())
      ;
    }
  };


__________________________________________________
Do you Yahoo!?
Yahoo! News - Today's headlines
http://news.yahoo.com




More information about the Cplusplus-sig mailing list