[C++-sig] shared_ptr and weak references

Artem Kulakov akulakov at creative-assembly.com.au
Fri Oct 1 08:21:29 CEST 2004


I have a problem with returning objects from C++ to Python via shared_ptr and 
using weak references on those objects. Here's what I am trying to do:

- create a new object in C++
- hold a shared_ptr to it in C++
- return the shared pointer to Python
- setup a weak reference to the object

My problem is that the weak reference turns dead once all Python variables 
pointing to the object are gone.

Any ideas?

Here is the source code:


#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/test/minimal.hpp>

#include <list>

using namespace boost::python;


struct Actor
{
	Actor()	{ std::cout << "  Actor::Actor" << std::endl; }
	~Actor() { std::cout << "  Actor::~Actor" << std::endl; }
};
typedef boost::shared_ptr<Actor> ActorPtr;

static std::list<ActorPtr> s_Actors;

ActorPtr NewActor()
{
	ActorPtr p(new Actor);
	s_Actors.push_back(p);
	return p;
}


BOOST_PYTHON_MODULE(cpp_impl)
{
	class_<Actor>("Actor");
	register_ptr_to_python<ActorPtr>();
	def("NewActor", &NewActor);
}

int test_main( int, char *[] )
{
	Py_Initialize();

	BOOST_REQUIRE(PyImport_AppendInittab("cpp_impl", initcpp_impl) != -1);

	handle<> main_module(borrowed( PyImport_AddModule("__main__") ));
	handle<> main_namespace(borrowed( PyModule_GetDict(main_module.get()) ));

	try
	{
		handle<>( PyRun_String(
			"print 'Hello world!'		\n"
			"from cpp_impl import *		\n"
			"a = NewActor()				\n"
			"print a					\n"
			"import weakref				\n"
			"r = weakref.ref(a)			\n"
			"print r					\n"
			"a1 = a						\n"
			"del a						\n"
			"print r					\n"
			"del a1						\n"
			"print r					\n"
			"", Py_file_input,
			main_namespace.get(), main_namespace.get()) );
	}
	catch (error_already_set)
	{
		PyErr_Print();
	}
	Py_Finalize();
	return 0;
}


-- 


Artem Kulakov
Senior Programmer
The Creative Assembly International
http://www.creative-assembly.com.au/




More information about the Cplusplus-sig mailing list