|
Boost.PythonHeader <boost/python/extract.hpp> |
extract
extract
synopsisextract
constructors and destructorextract
observer functionsExposes a mechanism for extracting C++ object values from
generalized Python objects. Note that
extract<
...>
can also be used to
"downcast" an object to some specific ObjectWrapper. Because
invoking a mutable python type with an argument of the same type
(e.g. list([1,2])
typically makes a copy of
the argument object, this may be the only way to access the ObjectWrapper's
interface on the original object.
extract
extract<T>
can be used to extract a value of
an arbitrary C++ type from an instance of object
. Two usages are supported:
extract<T>(o)
is a temporary object
which is implicitly convertible to T
(explicit conversion
is also available through the object's function-call
operator). However, if no conversion is available which can convert
o
to an object of type T
, a Python
TypeError
exception will be raised.
extract<T> x(o);
constructs an extractor
whose check()
member function can be used to ask whether
a conversion is available without causing an exception to be thrown.
extract
synopsisnamespace boost { namespace python { template <class T> struct extract { typedef unspecified result_type; extract(PyObject*); extract(object const&); result_type operator()() const; operator result_type() const; bool check() const; }; }}
extract
constructors and destructorextract(PyObject* p); extract(object const&);
p
is non-null.extract
observer functionsresult_type operator()() const; operator result_type() const;
result_type
, which is either T
or
T const&
.
result_type
corresponding to the one referenced by the stored pointer.error_already_set
and sets a TypeError
if no such conversion is
available. May also emit other unspecified exceptions thrown by
the converter which is actually used.bool check() const;
true
does not preclude an exception
being thrown from operator result_type()
or
operator()()
.false
only if no conversion from the
stored pointer to T
is available.#include <cstdio> using namespace boost::python; int Print(str s) { // extract a C string from the Python string object char const* c_str = extract<char const*>(s); // Print it using printf std::printf("%s\n", c_str); // Get the Python string's length and convert it to an int return extract<int>(s.attr("__len__")()) }The following example shows how extract can be used along with
class_<
...>
to create and access an instance of a wrapped C++ class.
struct X { X(int x) : v(x) {} int value() { return v; } private: int v; }; BOOST_PYTHON_MODULE(extract_ext) { object x_class( class_<X>("X", init<int>()) .def("value", &X::value)) ; // Instantiate an X object through the Python interface. // Its lifetime is now managed by x_obj. object x_obj = x_class(3); // Get a reference to the C++ object out of the Python object X& x = extract<X&>(x_obj); assert(x.value() == 3); }
Revised 15 November, 2002
© Copyright Dave Abrahams 2002.