...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
make_getter()
and
make_setter()
are the
functions used internally by class_<>::def_readonly
and
class_<>::def_readwrite
to produce
Python callable objects which wrap C++ data members.
template <class C, class D> object make_getter(D C::*pm); template <class C, class D, class Policies> object make_getter(D C::*pm, Policies const& policies);
Policies
is a model of CallPolicies.from_python
to
C*
, and returns the corresponding member D
member of the C
object, converted to_python
.
If policies
is supplied, it will be applied to the
function as described here. Otherwise,
the library attempts to determine whether D
is a
user-defined class type, and if so uses return_internal_reference<>
Policies
. Note that this test may inappropriately
choose return_internal_reference<>
in some cases
when D
is a smart pointer type. This is a known
defect.template <class D> object make_getter(D const& d); template <class D, class Policies> object make_getter(D const& d, Policies const& policies); template <class D> object make_getter(D const* p); template <class D, class Policies> object make_getter(D const* p, Policies const& policies);
Policies
is a model of CallPolicies.d
or *p
, converted
to_python
on demand. If policies
is supplied,
it will be applied to the function as described here. Otherwise, the library attempts to
determine whether D
is a user-defined class type, and if
so uses reference_existing_object
Policies
.template <class C, class D> object make_setter(D C::*pm); template <class C, class D, class Policies> object make_setter(D C::*pm, Policies const& policies);
Policies
is a model of CallPolicies.from_python
to C*
and
D const&
, respectively, and sets the
corresponding D
member of the C
object. If
policies
is supplied, it will be applied to the function
as described here.template <class D> object make_setter(D& d); template <class D, class Policies> object make_setter(D& d, Policies const& policies); template <class D> object make_setter(D* p); template <class D, class Policies> object make_setter(D* p, Policies const& policies);
Policies
is a model of CallPolicies.D const&
and written into d
or *p
, respectively. If
policies
is supplied, it will be applied to the function
as described here.The code below uses make_getter and make_setter to expose a data member as functions:
#include <boost/python/data_members.hpp> #include <boost/python/module.hpp> #include <boost/python/class.hpp> struct X { X(int x) : y(x) {} int y; }; using namespace boost::python; BOOST_PYTHON_MODULE_INIT(data_members_example) { class_<X>("X", init<int>()) .def("get", make_getter(&X::y)) .def("set", make_setter(&X::y)) ; }It can be used this way in Python:
>>> from data_members_example import * >>> x = X(1) >>> x.get() 1 >>> x.set(2) >>> x.get() 2
5 August, 2003
© Copyright Dave Abrahams 2002.