[C++-sig] Cross Module Inheritance and Downcast

Joseph Lisee jlisee at gmail.com
Fri Jan 11 19:28:28 CET 2008


Hello All,

I am having trouble getting cross module inheritance/downcasting to work.  All
of the following types are wrapped up in shared_ptrs.  Here is the code layout:

Shared Library A: Has the Base class.  It implements virtual functions of the
Base class.  It also has a factory which produces objects referred to by a Base
class shared_ptr.  This includes the ability to produce Derived class objects
referred to by the Base class shared_ptr. It *does not* link to "Shared Library
B", or know anything of the derived types.

Shared Library B: Has the Derived class and links to "Shared Library A".  It
implements virtual functions of the Derived class.

Extension Module A: This is linked to "Shared Library A".  The base class is
wrapped like so:

class BaseWrapper: public Base, public bp::wrapper< Base > {
   ... more code ...
}

void registerBaseClass() {
    bp::class_<BaseWrapper,
        bp::bases< ... more code ...>,
        boost::noncopyable >( ... more code ...).
    ... more code ...
}



Extension Module B: This is linked to both "Shared Library A", and "Shared
Library B".  It wraps the derived class like so:

struct Derived_wrapper : Derived, bp::wrapper< Derived > {
   ... more code ...
}

void register_Derived_class(){
    bp::class_< Derived_wrapper, 
        bp::bases< Base >, 
        boost::noncopyable >( ... more code ...).
    ... more code ...
}


This issue is that when I call the factory in "Extension Module A" from python
it only gives me the Base class objects.  It does not automatically downcast.  I
do have both the Base and Derived class extension modules imported, and I
imported the Base class one first.  I get this same behavior on Windows, Linux
and Mac.

So to fix this I tried to create a manual cast function:
boost::shared_ptr<Derived> castTo(boost::shared_ptr<Base> from) {
    return boost::dynamic_pointer_cast<Derived>(from);
}

Now the cast function works on Linux just fine, but on Windows and Mac it just
returns the same python object I give it.

Can anyone point me to how I should be doing this?  Has anyone got a system like
this to work?

-Joseph Lisee






More information about the Cplusplus-sig mailing list