[C++-sig] shared_ptr object identity

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Mon Aug 16 00:45:34 CEST 2010


Hi Erland,

> I've been bashing my head against a wall for the past couple of days

> trying to figure this out. It's frustrating because it seems like it
> should be such a simple thing.

I cannot be so simple if you think of the C++ side as being unaware of
the Python layer. Each time the C++ function is called Boost.Python has
to create a new Python object. I believe it is very difficult or maybe
even impossible to reliably return the same Python object like you expect.

> BarPtr getBar()
> {
>     return mBarInstance;
> }

I think your example can be made to work like this (untested):

In the file with the Python bindings:

boost::python::object getBar_wrapper()
{
  static boost::python::object result = getBar();
  return result;
}

With:

  def("getBar", getBar_wrapper);

But I've not tested it.

> Note that I am using a global mFooInstance for
> simplicity, but in reality such object will be held as members

That still seems doable, via a wrapper object.

> or in containers.

If you have pure C++ containers in mind I think it is possible only
via virtual functions that you override in a wrapper object.

But maybe the best solution is something else, without requiring object 
identity:

- Add all data attributes to the C++ object (and use .def_readonly() or 
.def_readwrite()).
  Then the state of the object is preserved naturally.

- Inject additional Python methods as described in the Boost.Python tutorial:

http://www.boost.org/doc/libs/1_43_0/libs/python/doc/tutorial/doc/html/python/techniques.html#python.extending_wrapped_objects_in_python


Ralf


More information about the Cplusplus-sig mailing list