Extracting C++ objects

| Extracting C++ objects

At some point, we will need to get C++ values out of object instances. This can be achieved with the `extract<T>` function. Consider the following:

`

        double x = o.attr("length"); // compile error

`

In the code above, we got a compiler error because Boost.Python `object` can't be implicitly converted to `double`s. Instead, what we wanted to do above can be achieved by writing:

`

        double l = extract<double>(o.attr("length"));
        Vec2& v = extract<Vec2&>(o);
        assert(l == v.length());

`

The first line attempts to extract the "length" attribute of the Boost.Python `object` `o`. The second line attempts to extract the `Vec2` object from held by the Boost.Python `object` `o`.

Take note that we said "attempt to" above. What if the Boost.Python `object` `o` does not really hold a `Vec2` type? This is certainly a possibility considering the dynamic nature of Python `object`s. To be on the safe side, if the C++ type can't be extracted, an appropriate exception is thrown. To avoid an exception, we need to test for extractibility:

`

        extract<Vec2&> x(o);
        if (x.check()) {
            Vec2& v = x(); ...

`

The astute reader might have noticed that the `extract<T>` facility in fact solves the mutable copying problem:

`

        dict d = extract<dict>(x.attr("__dict__"));
        d['whatever'] = 3;          ##modifies x.__dict__ !

`

Copyright © 2002-2003 David Abrahams
Copyright © 2002-2003 Joel de Guzman
Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.