dynamic_cast in python extension module [was dynamic_cast in shared library]

Toon Knapen toon.knapen@fft.be
Sun Oct 17 06:37:00 GMT 2004


(I'm sorry to repeat my question but my previous mail contained an error 
which made it not clear that it was dealing with a python extension 
module and thus made it hard to understand)


I'm encountering trouble when performing a dynamic_cast in a dynamic 
library (which is actually an extension module of python and is thus 
loaded by means of the import command in python).

I know about the -E option when linking the exe (which is a program with 
python embedded) and not using the -Bsymbolic. And the funny thing is 
that the dynamic_cast all of a sudden works when I allocate another 
object of the casted-to type. Let me explain:

Inside the python extension module, which is compiled in C++ while 
having external C linkage for integration in python (which is in C), I 
call a function that returns a boost::shared_ptr<Base> but which 
actually points to a Derived (where the class Derived is derived from 
Base as you could have guessed). So in pseudo-code following happens:

1) boost::shared_ptr< Base > ptr = some_function() ;
2) std::cout<<&typeid( *ptr )<<":"<<typeid(*ptr).name()<<std::endl;
3) Base* ptr2 = ptr.get() ;
4) std::cout<<&typeid( *ptr2 )<<":"<<typeid(*ptr2).name()<<std::endl;
5) Derived* ptr3 = dynamic_cast< Derived* >( ptr2 ) ;
6) std::cout<<&typeid(Derived)<<":"<<typeid(Derived).name()<<std::endl;
7) // Derived& ptr4 = new Derived

on line 2 and line 4, the same address is printed and the correct name 
is printed (i.e. Derived). However on line 5, the dynamic_cast fails and 
thus ptr3 is NULL. On line 6, the same name is printed as on line 2 and 
4 _but_ the address of the corresponding typeinfo object is different.

So line 5 and 6 give a surprising (at least to me) result. Now even more 
surprising is that uncommenting line 7 results in a succesfull 
dynamic_cast on line 5 and line 6 giving the exact same result as line 2 
and line 4.

I'm totally dazzled and have no idea why the dynamic_cast fails and how 
uncommenting line 7 can influence it. Also the type_info object 
corresponding to the Derived type is always (line 7 uncommented or not) 
in the corresponding shared library as a weak symbol (indicated with 'V' 
when using nm)

Any ideas would be greatly appreciated !?

some background info:
I'm using python 2.3.3 and gcc 3.2 (Redhat 8.0). The problem was also 
reproduced with gcc3.2.2 (Redhat 9.0) and python 2.4a3




More information about the Gcc-help mailing list