[C++-sig] Python + Boost Python V2 + downcasting
David Abrahams
dave at boost-consulting.com
Wed Nov 6 21:12:46 CET 2002
"Nicolas Lelong" <n_lelong at hotmail.com> writes:
> Hello,
>
> I'm experiencing some embedding+extending with BPLv2 - and I could
> not find any answer to this simple question :
>
> I have, say, a c++ class 'Base' and a c++ class 'Derived':
>
> class Base
> {
> public:
> virtual int do_stuff() { return 0; }
> };
>
> class Derived
> {
> public:
> virtual int do_more() { return 100; }
> };
>
> class ObjectServer
> {
> public:
> Base* getObject(unsigned id)
> {
> return m_objects[id];
> }
>
> Base* m_objects[12];
> }
>
> declared in my module like this:
>
> class_<Base>("Base")
> .def("do_stuff", &Base::do_stuff);
>
> class_<Derived, bases<Base> >("Derived")
> .def("do_more", &Derived::do_more);
>
> class_<ObjectServer>("ObjectServer")
> .def("getObject", &ObjectServer::getObject, return_internal_reference<>());
>
> everything works fine - except that I can't get python to see the
> _real_ class of the objects returned by getObject. I tried the
> following:
>
> ...
> obj = objectServer.getObject(0)
> print isinstance(obj, Base)
> print isinstance(obj, Derived)
> print issubclass(Derived, Base)
> print obj.__class__
>
> and I get, when 'obj' is really a 'Derived*'
> ...
> 1
> 0
> 1
> module.Base
>
> how can I get to know that an object is an instance of Derived ?!
Not easily. You could pass it to a function which takes a Derived& or
a Derived*.
> is there a builtin way in Python ? a BPL v2 way ?
Nope. It is holding a Base* internally, and using C++ runtime
polymorphism to call the right methods.
> I even thought about implementing my own 'isinstance' function but
> I'm not familiar enough with boost python & python !!... Any help or
> advice will be _greatly_ appreciated :)
Why do you need to do this? Such downcasting is usually the mark of a
poor design.
--
David Abrahams
dave at boost-consulting.com * http://www.boost-consulting.com
More information about the Cplusplus-sig
mailing list