[C++-sig] problem returning polymorphic shared_ptr instances

Jim Bosch talljimbo at gmail.com
Wed Jan 12 22:30:03 CET 2011


On 01/12/2011 12:06 PM, Matt Bendiksen wrote:
> Thanks Jim, but I still cannot get it to work. I now have it defined as:
>
>     def("get_a_or_b_instance", get_a_or_b_instance);
>     class_<A, boost::shared_ptr<A>  >("A", init<>())
>         ;
>     class_<B, boost::shared_ptr<B>, bases<A>  >("B", init<>())
>         ;
>
> (note I change your example line from "bases<B>" to "bases<A>")
>

Yeah, that's correct.  Error on my part.

> I tried it with and without:
>
>     register_ptr_to_python<  boost::shared_ptr<B>  >();
>
> But from Python whenever I call:
>
>     type(app.get_a_or_b_instance(True))
>
> I always get back:
>
>     <class 'app.A'>
>
> Any other ideas?
>

Yes.  I just remembered that the downcasting only works if your classes 
are polymorphic; otherwise dynamic_cast (which is the underlying 
mechanism) doesn't work.

Adding a virtual destructor to the base class would be sufficient.

Jim



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



More information about the Cplusplus-sig mailing list