与dlopen / dlsym一起使用时dynamic_cast失败 [英] dynamic_cast fails when used with dlopen/dlsym
问题描述
让我为这个长期的问题道歉。
Let me apologise upfront for the long question. It is as short as I could make it, which is, unfortunately, not very short.
我定义了两个接口A和B:
I have defined two interfaces, A and B:
class A // An interface
{
public:
virtual ~A() {}
virtual void whatever_A()=0;
};
class B // Another interface
{
public:
virtual ~B() {}
virtual void whatever_B()=0;
};
然后,我有一个共享的库 testc,构造了类C的对象,同时实现了A和B ,然后传递指向其A接口的指针:
Then, I have a shared library "testc" constructing objects of class C, implementing both A and B, and then passing out pointers to their A-interface:
class C: public A, public B
{
public:
C();
~C();
virtual void whatever_A();
virtual void whatever_B();
};
A* create()
{
return new C();
}
最后,我有第二个共享库 testd,它需要一个 A *
作为输入,并尝试使用 dynamic_cast 将其转换为
B *
code>
Finally, I have a second shared library "testd", which takes a A*
as input, and tries to cast it to a B*
, using dynamic_cast
void process(A* a)
{
B* b = dynamic_cast<B*>(a);
if(b)
b->whatever_B();
else
printf("Failed!\n");
}
最后,我有主应用程序,通过了 A *
在库之间:
Finally, I have main application, passing A*
's between the libraries:
A* a = create();
process(a);
问题
如果我构建主应用程序,链接到 testc和 testd库,一切按预期进行。但是,如果我修改主应用程序以不链接到'testc'和'testd',而是在运行时使用 dlopen
/ dlsym加载它们
,则 dynamic_cast
失败。
我不明白为什么。有任何线索吗?
I do not understand why. Any clues?
- 已通过gcc 4.4.1,libc6测试2.10.1(Ubuntu 9.10)
- 示例代码可用
- Tested with gcc 4.4.1, libc6 2.10.1 (Ubuntu 9.10)
- Example code available
推荐答案
我找到了问题的答案此处。据我了解,我需要将 testc中的typeinfo提供给 tested库。为此,在使用 dlopen()
时,还需要做两件事:
I found the answer to my question here. As I understand it, I need to make the typeinfo available in 'testc' available to the library 'testd'. To do this when using dlopen()
, two extra things need to be done:
- 链接库时,将链接器的
-E
选项传递给链接器,以确保将所有符号导出到可执行文件,而不只是导出未在其中解析的符号(因为 - 使用
dlopen()
加载库时,添加RTLD_GLOBAL
选项,以确保testc
导出的符号也可用于tested
- When linking the library, pass the linker the
-E
option, to make sure it exports all symbols to the executable, not just the ones that are unresolved in it (because there are none) - When loading the library with
dlopen()
, add theRTLD_GLOBAL
option, to make sure symbols exported bytestc
are also available totestd
这篇关于与dlopen / dlsym一起使用时dynamic_cast失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!