On Sat, 2010-03-20 at 21:31 +0100, peoro wrote:
> Hello,
> 
> I'm having some issues with shared_ptr's in a Python environment: it
> looks like once a shared_ptr enters Python, it cannot be upcasted nor
> downcasted.
> 
> Here's a brief C++ source code to explain better the issue:
> 
> 
> #include <boost/shared_ptr.hpp>
> 
> class Base { };
> class Derived : public Base { };
> 
> boost::shared_ptr<Base> base1( ) {
>   return boost::shared_ptr<Base>( new Base );
> }
> boost::shared_ptr<Base> base2( ) {
>   return boost::shared_ptr<Base>( new Derived );
> }
> boost::shared_ptr<Base> base3( boost::shared_ptr<Derived> derived ) {
>   return boost::shared_ptr<Base>( derived );
> }
> boost::shared_ptr<Derived> derived1( ) {
>   return boost::shared_ptr<Derived>( new Derived );
> }
> boost::shared_ptr<Derived> derived2( boost::shared_ptr<Base> base ) {
>   return boost::static_pointer_cast<Derived>( base );
> }
> 
> 
> then, after building the library and importing it into Python, I would
> expect something like this:
> 
> 
> from shared_ptr_inheritance import *
> type( base1() ) -> Base
> type( base2() ) -> Base
> type( derived1() ) -> Derived
> type( base3( derived1() ) ) -> Base
> type( derived2( base2() ) ) -> Derived
> 
> 
> but instead, this is the actual behaviour:
> 
> 
> from shared_ptr_inheritance import *
> type( base1() ) -> Base
> type( base2() ) -> Base
> type( derived1() ) -> Derived
> type( base3( derived1() ) ) -> Derived (!!!)
> type( derived2( base2() ) ) -> Base (!!!)
> 
> 
> am I doing something wrong?
> why does this happen, and, mostly, how can I cast a shared_ptr<Base>
> containing a Derived pointer, to shared_ptr<Derived> ?
> ______________________________________________

If you've wrapped all classes with shared_ptr storage, to-python
converts should always produce the most-derived type in Python, and I
think that's what you want on the Python side.  This may not work if you
can't use shared_ptr storage for some reason, or if you return an
intermediate class you haven't wrapped.

Are you using shared_ptr storage?


Jim Bosch

_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to