[C++-sig] boost.python: modifying class getattr

David Abrahams dave at boost-consulting.com
Wed Nov 16 18:37:30 CET 2005


Julien Sylvestre <jusylves at videotron.ca> writes:

> Hello all,
>     I'm trying to access the type structure for a c++ class exposed to
> Python using boost.python, so that I can have ob_type->tp_getattro point
> to a custom function instead of PyObject_GenericGetAttr (for those who
> wonder why, it's a performance issue: with my current project,
> PyObject_GenericGetAttr is always called first, fails to find the
> requested attribute, and then __getattr__ is called on the wrapped
> object, which returns the attribute. I get an extra PyString_FromFormatV
> for each access to an attribute value, and this slows down my code by ~20%)
>
> If I write:
> object Foo_ = class_<Foo>("Foo", init< >())
>       .def("__getattr__", &Foo::Foo_getattr)
>       .def("__setattr__", &Foo::Foo_setattr)
> ...,
>
> is there a way to modify the type object associated with Foo_ instances
> so that instead of calling PyObject_GenericGetAttr when an attribute is
> requested, Python calls a function
> PyObject *
> Foo_GetAttr(PyObject *obj, PyObject *name)
> ?

  PyTypeObject* Foo_t = (PyTypeObject*)Foo_.ptr();
  Foo_t->tp_getattro = Foo_GetAttr;

HTH,

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com




More information about the Cplusplus-sig mailing list