views:

422

answers:

2

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.

+7  A: 

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.

Xeor
When i use the flag RTLD_GLOBAL to dlopen i get dlerror: invalid mode for dlopen(): Invalid argument.void* handle = dlopen("myLib.so", RTLD_GLOBAL);This dlopen statement is in a shared library that my code calls.My code -> shared lib -> dynamically loads another lib with dlopen("myLib.so", RTLD_GLOBAL);
Rob Smith
I now use:void* handle = dlopen("myLib.so", RTLD_NOW | RTLD_GLOBAL);And it does compile but i still cant catch exceptions thrown by myLib.so
Rob Smith
Which type of exception do you throw? Your custom one? Maybe you can update question with short sample code? And also with version of system and compiler
Xeor
+1  A: 
AlexKR
I compile everything with -shared -fPIC -W1, --export-dynamic -W1, -soname, libTest.soBut I am not sure at all about these flags.I have added -rdynamic and tested but i still cant catch exceptions:-shared -fPIC -W1, -rdynamic --export-dynamic -W1, -soname, libTest.so
Rob Smith