如何避免在调用 .so 中抛出异常的函数时崩溃
这就是我所做的,我想优雅地处理这个异常:
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;
}
从上面的两个片段中,我使用以下命令创建了一个shared_object libexception.so:
g++ -c -fPIC src/my.cpp
gcc -c -ansi -fPIC src/exception.c
g++ -fPIC -shared -o libexception.so
然后我从我的main调用了函数so_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;
}
最终命令: g++ -g -ldl -o main.exe src/main.cpp -L lib/ -lexception
执行 main.exe 崩溃。有人可以帮我检测问题出在哪里以及如何避免发生这种崩溃(我们已经有一些架构,其中一些 .SO 调用 extern c++ 函数,因此无法更改,我们只想在 main.cpp 中处理它)
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, "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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用
-fexception
编译src/exception.c
Try compiling
src/exception.c
with-fexceptions
该函数可能会抛出一个不是 char* 的异常,因此您无法捕获它。
尝试使用通用捕获:
That function probably throws an exception that is not char* so you're not catching it.
try using a generalized catch: