2011-06-17 19 views
3

這裏拋出異常是我做的崩潰,我想優雅地處理這個異常:如何避免在調用函數的。所以

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.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 -ldl -o MAIN.EXE SRC /主.cpp -L lib/-lexception

執行main.exe崩潰。有人可以幫助我檢測問題的出在哪裏,以及如何避免這種崩潰發生(我們已經有一些架構,其中一些.SO調用extern C++函數,所以不能更改,我們只想在main.cpp中處理它)

回答

5

嘗試編譯src/exception.c-fexceptions

+0

是這個作品,謝謝。 – pankiii 2011-06-17 07:39:34

+0

@pankiii:請不要忘記**接受**回答:) – ereOn 2011-06-17 07:50:34

2

該函數可能會拋出一個不是的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" 
    } 
+0

問題仍然會出現... – pankiii 2011-06-17 07:39:15