help-gplusplus
[Top][All Lists]
Advanced

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

dynamic_cast problem


From: KeithO
Subject: dynamic_cast problem
Date: Sat, 3 Jul 2004 00:52:05 +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





reply via email to

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