This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
dynamic_cast in shared library
- From: Toon Knapen <toon dot knapen at fft dot be>
- To: gcc-help at gcc dot gnu dot org
- Date: Fri, 15 Oct 2004 22:32:47 +0200
- Subject: dynamic_cast in shared library
I'm encountering trouble when performing a dynamic_cast in a dynamic
library (which is actually an extension module of femtown 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 of course 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. 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 !?