4

これが私がしたことです、私はこの例外を優雅に処理したいと思います:

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;
}

上記の2つのスニペットから、次のコマンドを使用してshared_objectlibexception.soを作成しました。

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

次に、main.cpp code_snippet:main.cppから関数so_mainを呼び出しました。

#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でのみ処理します) )。

4

2 に答える 2

6

でコンパイルsrc/exception.cしてみてください-fexceptions

-fexceptions例外処理を有効にします。例外を伝播するために必要な追加のコードを生成します。一部のターゲットでは、これはGNUCCがすべての関数のフレームアンワインド情報を生成することを意味します...

ただし、C ++で記述された例外ハンドラーと適切に相互運用する必要があるCコードをコンパイルする場合は、このオプションを有効にする必要があります。例外処理を使用しない古いC++プログラムをコンパイルする場合は、このオプションを無効にすることもできます。

于 2011-06-17T07:30:37.690 に答える
1

その関数はおそらく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"
    }
于 2011-06-17T07:34:21.683 に答える