如何捕获GCC C ++中从库抛出的异常? [英] How to catch exception thrown from library in GCC C++?

查看:103
本文介绍了如何捕获GCC C ++中从库抛出的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用dlopen动态加载库时,似乎无法捕获该库引发的异常。据我了解,这是因为dlopen是C函数。

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.

是否存在另一种动态加载库的方法,该库可以捕获lib在GCC中引发的异常?

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

在Windows中,您可以使用LoadLibrary,但对于Linux,我只找到了dlopen,但是使用dlopen时,我无法捕获异常。

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

编辑
我尝试过void * handle = dlopen( myLib.so,RTLD_NOW | RTLD_GLOBAL);而且我仍然无法捕捉到myLib.so

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 引发的异常:
我使用其自己的命名空间抛出了自定义异常。我希望能够在库外捕获这些异常。
我希望能够在不同的编译器上进行编译,例如GCC 3.2和GCC 4.1。

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.

在myLib2.so中,我抛出了异常,例如: / p>

In myLib2.so i throw exceptions, one example:

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

在myLib1.so中,我想捕获该异常:

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动态加载myLib2.so:

mylib1.so dynamically loads myLib2.so with:

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

在Windows中有效(以捕获我的例外),但是我没有当然使用dlopen。

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

编辑3 :myLib1.so是动态链接的。

Edit 3: myLib1.so is dynamically linked.

推荐答案

您需要为dlopen指定RTLD_GLOBAL标志。这将允许正确的弱符号绑定,因此异常对象的每个typeinfo符号都指向同一位置,这是异常处理ABI代码所需要的。

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.

这篇关于如何捕获GCC C ++中从库抛出的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆