Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of boost. Click here for the latest Boost documentation.
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 doubles. 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 objects. 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__ !