开发者

How to avoid crashing while calling function throwing exception from .so

Here is what I did, I want to gracefully handle this exception:

code_snippet: my.cpp

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

code_snippet: exception.c

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

From above two snippets I have created a shared_object libexception.so by using following commands:

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

Then I called the function so_main from my main.cpp code_snippet: 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开发者_StackOverflow社区, "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;

}

final command: g++ -g -ldl -o main.exe src/main.cpp -L lib/ -lexception

Executing main.exe crashes. Can somebody help me detect where the problem lies and how to avoid this crash to happen (We have already some architecture where some .SO calls extern c++ function, so that can't be changed, We want to handle it in main.cpp only)


Try compiling src/exception.c with -fexceptions

-fexceptions Enable exception handling. Generates extra code needed to propagate exceptions. For some targets, this implies GNU CC will generate frame unwind information for all functions ...

However, you may need to enable this option when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable this option if you are compiling older C++ programs that don't use exception handling.


That function probably throws an exception that is not char* so you're not catching it.

try using a generalized 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"
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜