help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: dynamic_cast problem


From: Bernd Strieder
Subject: Re: dynamic_cast problem
Date: Fri, 07 Jul 2006 12:07:52 +0200
User-agent: KNode/0.10.2

Hello,

Earl Purple wrote:

> I think this has been addressed before but not for 2 years.
> 
> I have a model whereby I dynamically load libraries with dlopen then
> verify that they are the correct types with dynamic_cast.

Just verifying should not be necessary.

> 
> dynamic_cast seems to be failing though with gcc (I am using 3.2.1
> because that is the version we have here that also works with purify).
> 

Looking at

http://www.isotton.com/howtos/C++-dlopen-mini-HOWTO/C++-dlopen-mini-HOWTO.html

which tries to provide a portable solution:

You probably have a virtual base class, and you have a derived class
being passed through base class pointers. If both classes have to be
exposed to the executable, then they could be passed from the plugin
independently, by factory methods of their own, and no casting would be
necessary.

A second option might be a user-defined cast, i.e. a virtual member
function in the base class returning a pointer to the derived class,
returning 0 by default, overwritten in the derived class to do the
right thing.

Both options have the disadvantage, that those classes you want to be
able to cast to become part of the overall plugin interface. It would
not work, if all plugins required it.

A third option for verifying purposes could be a user-defined rtti
function returning a specific id for every class.

Another option might be following the ideas of the HOWTO above. There
should be functions to create and destroy objects from the plugin. The
cast could be implemented in another function extern "C" in the plugin.
This seems to have the advantage that the base class is not cluttered
up. If you want to use dynamic_cast, you should know the class to be
expected, and what plugin it is to be expected from, so you can call
the right casting function.

Whatever, a not failing dynamic_cast has to be in the code of the
plugin.

> Whilst I normally don't cast at all in my code, this is the one
> occasion I do - I have built this type of model twice before,
> successfully using Solaris compiler (which has all sorts of other
> problems) and also on VC7 (obviously using LoadLibrary() etc) and it
> worked then.

dynamic_cast is necessary in some cases, or it would not exist. Coding
around it is about as ugly as the cast itself.

Bernd Strieder



reply via email to

[Prev in Thread] Current Thread [Next in Thread]