1 [section boost/python/has_back_reference.hpp]
3 <boost/python/has_back_reference.hpp> defines the predicate metafunction `has_back_reference<>`, which can be specialized by the user to indicate that a wrapped class instance holds a `PyObject*` corresponding to a Python object.
5 [section Class template `has_back_reference`]
6 A unary metafunction whose value is true iff its argument is a `pointer_wrapper<>`.
8 namespace boost { namespace python
10 template<class WrappedClass> class has_back_reference
12 typedef mpl::false_ type;
17 A metafunction that is inspected by Boost.Python to determine how wrapped classes can be constructed.
19 `type::value` is an integral constant convertible to bool of unspecified type.
20 Specializations may substitute a true-valued integral constant wrapper for type iff for each invocation of `class_<WrappedClass>::def(init< type-sequence...>())` and the implicitly wrapped copy constructor (unless it is noncopyable), there exists a corresponding constructor `WrappedClass::WrappedClass(PyObject*, type-sequence...)`. If such a specialization exists, the WrappedClass constructors will be called with a "back reference" pointer to the corresponding Python object whenever they are invoked from Python. The easiest way to provide this nested type is to derive the specialization from `mpl::true_`.
26 #include <boost/python/class.hpp>
27 #include <boost/python/module.hpp>
28 #include <boost/python/has_back_reference.hpp>
29 #include <boost/python/handle.hpp>
30 #include <boost/shared_ptr.hpp>
32 using namespace boost::python;
33 using boost::shared_ptr;
37 X(PyObject* self) : m_self(self), m_x(0) {}
38 X(PyObject* self, int x) : m_self(self), m_x(x) {}
39 X(PyObject* self, X const& other) : m_self(self), m_x(other.m_x) {}
41 handle<> self() { return handle<>(borrowed(m_self)); }
42 int get() { return m_x; }
43 void set(int x) { m_x = x; }
49 // specialize has_back_reference for X
50 namespace boost { namespace python
53 struct has_back_reference<X>
62 int get() { return m_x; }
63 void set(int x) { m_x = x; }
69 Y_self(shared_ptr<Y> self) { return self; }
71 BOOST_PYTHON_MODULE(back_references)
75 .def("self", &X::self)
80 class_<Y, shared_ptr<Y> >("Y")
88 The following Python session illustrates that x.self() returns the same Python object on which it is invoked, while y.self() must create a new Python object which refers to the same Y instance.
92 >>> from back_references import *
97 >>> (x.get(), x2.get())
100 >>> (x.get(), x2.get())
108 >>> (y.get(), y2.get())
111 >>> (y.get(), y2.get())