4

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

code_snippet:我的.cpp

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

code_snippet:异常.c

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

从上面的两个片段中,我使用以下命令创建了一个 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 code_snippet 中调用了函数 so_main: 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 中处理它)

4

2 回答 2

6

src/exception.c尝试编译-fexceptions

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

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

于 2011-06-17T07:30:37.690 回答
1

该函数可能会引发不是char*的异常,因此您没有捕获它。

尝试使用广义捕获:

   *(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"
    }
于 2011-06-17T07:34:21.683 回答