【问题标题】:How to avoid crashing while calling function throwing exception from .so从.so调用抛出异常的函数时如何避免崩溃
【发布时间】:2011-06-17 07:25:46
【问题描述】:

这是我所做的,我想优雅地处理这个异常:

code_sn-p: my.cpp

#include<iostream>
extern "C" void some_func()
{
    throw "(Exception Thrown by some_func!!)";
}

code_sn-p: exception.c

#include <stdio.h>
extern void some_func();
int so_main()
{
    some_func();
    return 0;
}

从上面的两个 sn-ps 中,我使用以下命令创建了一个 shared_object libexception.so:

g++ -c -fPIC src/my.cpp
gcc -c -ansi -fPIC src/exception.c
g++ -fPIC -shared -o libexception.so

然后我从 main.cpp 中调用了函数 so_main code_sn -p: main.cpp

#include<iostream>
#include <dlfcn.h>
using namespace std;
extern "C" void some_func();
int main()
{
    int (*fptr)() = 0;
    void *lib = dlopen("./libexception.so", RTLD_LAZY);
    if (lib) {
        *(void **)(&fptr) = dlsym(lib, "so_main");
        try{
           if(fptr) (*fptr)();    <-- problem lies here
           //some_func();        <-- calling this directly won't crash
        }
        catch (char const* exception) {
            cout<<"Caught exception :"<<exception<<endl;
        }
    }
return 0;

}

最终命令:g++ -g -ldl -o main.exe src/main.cpp -L lib/ -lexception

执行 main.exe 崩溃。有人可以帮我检测问题出在哪里以及如何避免发生这种崩溃(我们已经有一些架构,其中一些 .SO 调用 extern c++ 函数,因此无法更改,我们只想在 main.cpp 中处理它)

【问题讨论】:

    标签: c++ c exception-handling unhandled-exception


    【解决方案1】:

    尝试用-fexceptions编译src/exception.c

    -f异常 启用异常处理。生成传播异常所需的额外代码。对于某些目标,这意味着 GNU CC 将为所有函数生成帧展开信息...

    但是,在编译需要与用 C++ 编写的异常处理程序正确互操作的 C 代码时,您可能需要启用此选项。如果您正在编译不使用异常处理的旧 C++ 程序,您可能还希望禁用此选项。

    【讨论】:

      【解决方案2】:

      该函数可能会抛出一个不是 char* 的异常,所以你没有捕捉到它。

      尝试使用广义的 catch:

         *(void **)(&fptr) = dlsym(lib, "so_main");
          try{
             if(fptr) (*fptr)();    <-- problem lies here
             //some_func();        <-- calling this directly won't crash
          }
          catch (char const* exception) {
              cout<<"Caught exception :"<<exception<<endl;
          }
          catch (...) {
              cout<<"Caught exception : Some other exception"
          }
      

      【讨论】:

        猜你喜欢
        • 2022-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-18
        • 1970-01-01
        • 2022-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多