Will C++ exceptions safely propagate through C code?

前端 未结 5 748
傲寒
傲寒 2020-11-28 11:44

I have a C++ application that calls SQLite\'s (SQLite is in C) sqlite3_exec() which in turn can call my callback function implemented in C++. SQLite is compiled into a stati

5条回答
  •  孤城傲影
    2020-11-28 12:11

    That was a really interesting question and I tested it out myself out of curiosity. On my OS X w/ gcc 4.2.1 the answer was YES. It works perfectly. I think a real test would be using gcc for the C++ and some other (MSVC?, LLVM?) for the C part and see if it still works.

    My code:

    callb.h:

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    typedef void (*t_callb)();
    void cfun(t_callb fn);
    
    #ifdef __cplusplus
    }
    #endif
    

    callb.c:

    #include "callb.h"
    
    void cfun(t_callb fn) {
     fn();
    }
    

    main.cpp:

    #include 
    #include 
    #include "callb.h"
    
    void myfn() {
      std::string s( "My Callb Except" );
      throw s;
    }
    
    int main() {
      try {
        cfun(myfn); 
      }
      catch(std::string s) {
        std::cout << "Caught: " << s << std::endl;
      }
      return 0;
    }
    

提交回复
热议问题