[C++-sig] keeping weak_ptrs upon python objects smart_ptr holders

Nicolas LELONG nico_ml at mgdesign.org
Wed Nov 19 14:00:17 CET 2003

Hi everyone,

I've been trying to wrap my Observer pattern implementation with BPL. I'm
willing to be able to create new observers in Python.
My listeners objects keep weak_ptrs upon their observers, these weak_ptrs
are used to notify the observers and to be able to know if a given observer
is still "alive".

I have not been able to obtain a weak_ptr that references the real
shared_ptr holding the observer objects. The weak_ptrs I get seem to
reference a dummy smart_ptr which is destoyed after the execution of

The 'problem' can be seen with the following code :

**** c++ code **********************************************

struct A
    virtual ~A(){}
    virtual std::string f() = 0;

struct ACallback :  A,  Callback
    ACallback (PyObject* self) : Callback(self) {}

    std::string f()
      object self(handle<>(borrowed(mSelf)));
      return extract<std::string>(self.attr("f")());

boost::weak_ptr<A> instance;

void setInstance(boost::shared_ptr<A> a) { instance = a; };

std::string doInstance()
  boost::shared_ptr<A> a = instance.lock();
  if (a.get() == NULL)
    return "no more object here!";
    return a->f();

  class_<A, ACallback, boost::noncopyable>("A")
    .def("f", pure_virtual(&A::f));

  def("setInstance", setInstance);
  def("doInstance", doInstance);

******** python script ***************************

from test import *

class E(A):
  def f(self):
    return 'E::f'

e = E()
res0 = doInstance()
res1 = e.f()


At the end of the script, res0 contains 'no more object here!' and res1
contains what I'd like res0 to contain : 'E::f' !

I did not find any information that could help me to solve this problem.
Is there any known way to achieve this or am I doomed to get rid of
weak_ptrs ?!


More information about the Cplusplus-sig mailing list