dynamic_cast problem

From: KeithO (kowen_at_nildram.co.uk)
Date: 07/02/04


Date: Fri, 2 Jul 2004 20:40:13 +0100

I am having problems calling dynamic_cast<> on a pointer returned by a
dynamically loaded library.
The problem seems to be related to the fact that I dynamically load the
library because if I link the app with the library it
works fine.

I am using gcc3.04 compiler on Linux AS2.1
The code works fine with MS VC6.0 and also with SunPro5.3 compilers.
The library contains a base class and a derived class and also an extern "C"
function that returns a pointer
to an instance of the derived class.
I then try to dynamically cast this pointer to the derived class which
fails.

Here is my library.
// dynalib.h
class DestinationImpl {
public:
    virtual char * getName();
};
class Destination_tib : public DestinationImpl {
public:
    char * getName();
    virtual char * getTibName();
};
extern "C" DestinationImpl * getDestinationImpl(void);

// dynalib.cpp
#include "dynalib.h"
char * DestinationImpl::getName() { return "DestinationImpl";}
char * Destination_tib::getName() { return "Destination_tib"; }
char * Destination_tib::getTibName() { return "TibName"; }
extern "C" DestinationImpl * getDestinationImpl(void) {return new
Destination_tib;}

Here is my test app.
#include "dynalib.h"
typedef void * (*MODULE_HANDLE)();
int main() {
    void * hdll=dlopen("libdynalib.so", RTLD_LAZY|RTLD_GLOBAL );
    MODULE_HANDLE fn = (void *(*)())dlsym(hdll, "getDestinationImpl");
    DestinationImpl * pDestImpl;
    if (fn) { pDestImpl = (DestinationImpl *)(fn()); }
    Destination_tib * p = dynamic_cast<Destination_tib *>(pDestImpl); //
This fails p == 0
}

Here is my makefile
 g++3 -g -Wall -shared -fPIC dynalib.cpp -I. -o libdynalib.so
 g++3 -g -Wall -I. -L. test.cpp -ldl -o test

Is there some linker option I can specify to make this work?

Thanks in advance.

Keith



Relevant Pages

  • Re: Virtual Data?
    ... > pointer to function. ... type of data for a member variable of the same name, ... But your derived class needs a more complicated variable x, ... virtual Init(const int initX); ...
    (comp.lang.cpp)
  • Re: Un-ringing the bell: making parent methods unavailable to children
    ... course making the method private in the derived class will prevent it from ... > to one type of data structure as a pointer to another type via overriding ... > Addunless it is type case as its parent class. ... > polymorphism in general. ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Copy of derived object from pointer to base
    ... > Larry Brasfield wrote: ... >> The reason to return a pointer whose type is pointer to the ... >> derived class is to make the Clone() method usable, ...
    (microsoft.public.vc.language)
  • Re: inheritance
    ... > constructors of a base class are not also members of the derived class. ... side is _converted_ to A* using the standard "pointer to derived to pointer ... to base" conversion. ...
    (comp.lang.cpp)