How to catch exception thrown from library in GCC C++?

北战南征 提交于 2019-12-18 13:37:59

问题


When i use dlopen to dynamically load a library it seems i can not catch exceptions thrown by that library. As i understand it it's because dlopen is a C function.

Is there another way to dynamically load a library that makes it possible to catch exceptions thrown by the lib in GCC?

In Windows you can use LoadLibrary but for Linux i have only found dlopen but when using dlopen i can not catch exceptions.

Edit: I have tried void* handle = dlopen("myLib.so", RTLD_NOW | RTLD_GLOBAL); and I still cant catch exceptions thrown by myLib.so

Edit 2: I throw custom exceptions with its own namespace. I want to be able to catch these exceptions outside the library. I want to be able to compile on different compilers, for example GCC 3.2 and GCC 4.1.

In myLib2.so i throw exceptions, one example:

namespace MyNamespace {  
    void MyClass::function1() throw(Exception1) {  
        throw Exception1("Error message");  
    } 
}

In myLib1.so I want to catch that exception:

std::auto_ptr <MyNamespace::MyClass> obj = MyNamespace::getClass();
try {  
    obj->function1();  
} catch (MyNamespace::Exception1& e) {  
    std::cout << e.what();  //This is not caught for some reason.  
}

mylib1.so dynamically loads myLib2.so with:

void* handle = dlopen("myLib2.so", RTLDNOW | RTLDGLOBAL);

This works in Windows (to catch my exceptions) but there I dont use dlopen of course.

Edit 3: myLib1.so is dynamically linked.


回答1:


You need to specify RTLD_GLOBAL flag to dlopen. This will allow correct weak symbol binding, so each typeinfo symbol for exception object will point at the same place, which is needed by exception processing ABI code.




回答2:


This depends on the version of GCC you are using.
First of all, make sure you compile everything with "-fPIC" and link with the "-rdynamic" flag.
RTLD_NOW flag is still needed.



来源:https://stackoverflow.com/questions/1740661/how-to-catch-exception-thrown-from-library-in-gcc-c

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