[C++-sig] shared_ptr object identity

Erlend Cleveland erlend.cleveland at gmail.com
Sun Aug 15 23:33:39 CEST 2010


Hi all,

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've also read through every archived
message I can find relating to this topic, but just can't seem to pull
it all together.

Here is a minimal example showing what I'm trying to do:

---------------------------------------------------------------
C++:

#include <boost/shared_ptr.hpp>

class Bar
{};

typedef boost::shared_ptr<Bar> BarPtr;

BarPtr mFooInstance = BarPtr(new Bar());

BarPtr getBar()
{
    return mBarInstance;
}

--------------------------------------------------------------
C++ / Python binding:

#include <boost/python.hpp>

using namespace boost::python;

BOOST_PYTHON_MODULE(Foo)
{
    class_<Bar, boost::noncopyable>("Bar", no_init);

    def("getBar", &getBar);

    register_ptr_to_python<BarPtr>();
}

--------------------------------------------------------------
Python:

import Foo

bar1 = Foo.getBar()
bar2 = Foo.getBar()

assert bar1 == bar2    # Assert fails due to bar1 and bar2 having
separate python objects

All I would like to achieve is for bar1 and bar2 to point to the same
python object, in the case where the object was created on the C++
side, such that I can add python attributes to such instances and have
this state preserved. Note that I am using a global mFooInstance for
simplicity, but in reality such object will be held as members or in
containers.

Thanks in advance for any help!


More information about the Cplusplus-sig mailing list