Differences between revisions 3 and 4
Revision 3 as of 2007-11-30 00:09:28
Size: 1637
Editor: 202-136-97-187
Comment: Added an example of complex nested data structure value extraction.
Revision 4 as of 2008-11-15 14:00:41
Size: 1637
Editor: localhost
Comment: converted to 1.6 markup
No differences found!

extractor interface which can be used to extract C++ types from Python objects.

We have discussed two main use cases for extractions

1. In user code which needs to retrieve C++ objects from their corresponding Python objects:

  1. Getting value:
    •     void f(object x)
          {
              int y = extract<int>(x); // retrieve an int from x
          }
  2. Users may also want to explicitly check for convertibility:
    •     int g(object x)
          {
              extract<int> get_int(x);
              if (get_int.check())
                  return get_int();
              else
                  return 0;
          }

Example:

  • In order to extract elements out of complex structures such as lists and tuples, we must nest extraction calls. The reason for this example is that it may not be immediately obvious to do this. Let's say you have a C++ class that contains a python-usable boost::python::list:

class A {
public:
  boost::python::list list;
  void listOperation(list& l);
};

Then you expose the class to python as:

class_<A>("A")
  .def_readwrite("b", &A::list)
  .def("op", &A::listOperation)
;

It is completely reasonable for python script to do something like this:

a = A()
a.b = [(1,2),(3,4),(5,6)]
a.op(a.b)

In order for you to extract the elements of tuples within the list, we use the index operator of the list:

void A::listOperation(list& l) {
   // Extract first element of first tuple in the list.
   extract<int>(extract<tuple>(list[0])())();
}

2. In the implementation of sequence from_python converters (e.g. Python tuple/list -> std::vector)

boost.python/extract (last edited 2012-02-28 15:53:49 by 195)

Unable to edit the page? See the FrontPage for instructions.