这是我所做的,我想优雅地处理这个异常:
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 中处理它)