[C++-sig] weak_ptr/shared_from_this and boost.python

a_python_coder zreed1 at gmail.com
Sat Jul 7 22:28:36 CEST 2007


Ive been having a devil of a time trying to get boost python to do the right
thing when I try to manipulate C++ objects with weak pointers. Ive narrowed
the issue down to a short test case below. Anyone have any ideas?


/* *************************************************** */
#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

using namespace std;
using namespace boost;
using namespace python;

struct XYZ
	: public enable_shared_from_this<XYZ>
{

	static shared_ptr<XYZ> construct()
	{
		s_instance = new XYZ;
		shared_ptr<XYZ> xyz( s_instance );
		// return a shared_ptr that manages the python object
		return extract< shared_ptr<XYZ> >( object(xyz) );
	}

	static shared_ptr<XYZ> get()
	{
		return shared_ptr<XYZ>( s_instance->shared_from_this() );
	}

	static XYZ* s_instance;

};

XYZ* XYZ::s_instance = 0;


BOOST_PYTHON_MODULE( test )
{
	class_< 
		  XYZ
		, shared_ptr<XYZ> 
		, noncopyable
		>( "XYZ", no_init )
		;
	
	def( "construct", &XYZ::construct );
	def( "get", &XYZ::get );

}

/* *************************************************** */

n [1]: import test

In [2]: x = test.construct()

In [3]: x
Out[3]: <test.XYZ object at 0x2ac8c0367a28>

In [4]: y = test.get()
---------------------------------------------------------------------------
exceptions.RuntimeError                              Traceback (most recent
call last)

/home/ym/tmp/<ipython console>

RuntimeError: tr1::bad_weak_ptr









-- 
View this message in context: http://www.nabble.com/weak_ptr-shared_from_this-and-boost.python-tf4041746.html#a11481937
Sent from the Python - c++-sig mailing list archive at Nabble.com.




More information about the Cplusplus-sig mailing list