RTLD_LOCAL and dynamic_cast on Linux

☆樱花仙子☆ 提交于 2019-12-04 11:34:43

Ok, what we finally did is kind of worked around the problem.

We added to the classes that we want to dynamic_cast() two static functions:

static MyClass* doNew();
static MyClass* doDynCast(MyBase*);

These were implemented in the cpp file which kept the new, the dynamic_cast() and the type_info object in the same lib and thus making the dynamic_cast() work around the problem.

This solution was enough for our specific case but if anyone has a more general solution it will be welcomed.

Another option that we found is to put all the implementation of the class in the cpp file which make the typeinfo symbol be present only in one library and all other libraries reference it only. This results in a successful dynamic_cast().

Unfortunately, because type_info structures are weak symbols local to the library that creates them, it's not easily possible to make dynamic_cast work. You might try manipulating where the class vtable (and type_info) is instantiated however; on GCC, this can be done by ensuring the first non-inline function in the class (in order of definition) is defined only in the common shared dependency library. If your class has no non-inline functions, create a dummy one just to force this generation to occur. Note however, that I haven't tested this and so can't guarantee that it will work. Additionally, this is compiler-dependent; I don't know what Intel's compiler does.

You could, of course, implement your own alternate dynamic casting mechanism using class names instead; there are a number of libraries which do this as well, such as Qt's qobject_cast.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!