dynamic_cast() between a program and a dlopen()ed library

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

 



Hi there,

I was wondering if anyone could shed some light on a problem I'm having.
I can't seem to get dynamic_cast() to downcast an object returned from a
library loaded with dlopen(). I was wondering if this is expected
behaviour or a bug I'm seeing? From what I've read on the web, I think
it *should* work.

Some code will illustrate the problem. The code included below can be
compiled with the following commands:
	g++ -g -o test test.cpp -ldl
	g++ --shared -fPIC -g -o lib.so lib.cpp

When you run 'test', you would expect the downcasts in create() and
main() to work, but only the one in the library does. For example, when
I run 'test', I get the following:
	1st dynamic_cast() returns: 0x13b8670
	2nd dynamic_cast() returns: 0

Does anyone know why this is?

Thanks is advance!


---------- class.h ----------

#include <string>

class B
{
public:
	B()
	{ _name = "B"; }
	virtual ~B()
	{ }
	std::string _name;
};

class D: public B
{
public:
	D()
	{ _name = "D"; }
};

---------- end ----------
---------- test.cpp ----------

#include <iostream>
#include <dlfcn.h>
#include "class.h"

typedef B *(*create_func)();

int main( void )
{
	void *h = dlopen( "./lib.so", RTLD_LAZY );
	if( !h ) {
		std::cerr << "dlopen(): " << dlerror() << "\n";
		return 1;
	}

	create_func func = (create_func)dlsym( h, "create" );
	if( !func ) {
		std::cerr << "dlsym(): " << dlerror() << "\n";
		return 1;
	}
	
	D *d = dynamic_cast< D * >( func() );
	std::cout << "2nd dynamic_cast() returns: " << d << "\n";
	return 0;
}

---------- end ----------
---------- lib.cpp ----------

#include "class.h"
#include <iostream>

extern "C" B *create()
{
	D *d = new D;
	std::cout << "1st dynamic_cast() returns: " << d << "\n";
	return d;
}

---------- end ----------


-- 
  edam  -  www.waxworlds.org/edam

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux