Avoiding crashes when calling 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;
}

Over two fragments, I created shared_object libexception.so using the 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 so_main function 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, "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

Main.exe is failing. Can someone help me determine where the problem lies and how to avoid this failure (we already have some architecture where some .SO calls the extern C ++ function, so it cannot be changed, we only want to process it in main.cpp)

+3
source share
2 answers

src/exception.c -fexceptions?

+5

, , , 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"
    }
+2

All Articles