c++ - Is this "trick" to throw exceptions across DLL boundaries a bad idea? -


i building shared library want abi compatible between different compilers (like msvc , gcc on windows). took inspiration this blog post. thing missed ability throw exceptions across dll boundaries... made little trick :

mylibrary.hpp

class thrower{     static void(*m_thowfunc)(const char*);  public:     static void setthrowfunction(void(*func)(const char*)){         m_thowfunc = func;     }      static void throwexception(const char* msg){         m_thowfunc(msg);     } };  extern "c" {     export void mylibrary_setthrowfunction(void(*func)(const char*));     export void mylibrary_foo(); } 

mylibrary.cpp

extern "c" {     export void mylibrary_setthrowfunction(void(*func)(const char*)){         thrower::setthrowfunction(func);     }      export void mylibrary_foo(){         thrower::throwexception("oops, error occured...");     } } 

and in client code

void defaultthrowfunction(const char* msg){     throw std::runtime_error(msg); }  int main(){     mylibrary_setthrowfunction(&defaultthrowfunction);     try{         mylibrary_foo();     }catch(std::runtime_error& e){         //handle exception     } } 

this works charm. can handle exceptions thrown dll (in fact, thrown client code) in client code. downside aware of have tons of warnings while compiling dll since "not control path return value"...

am missing here ? idea or not @ ?

this may work, if throwing mechanism , stack unrolling code of 2 code bases identical , compatible.

in order destroy each of objects should after throw, client code has able understand how dll code sets stack , registers destructors cleaned up, etc. may case client , dll code compilers sufficiently in agreement work, if lucky.

which sort of ruins point of design.


an approach might work marshal exceptions on dll boundary.

the "c" api dll returns information exceptions (if any) thrown. c++ header-file wrapper client compiles calls "c" api, , in client-compiled code detects exception, unwraps it, , throws it.

inside dll, "c" api try{}catch(){}, , calls internal c++ library. catch clause populates exception information "c" api return value, , returns.

now internal exceptions thrown, caught within c++ dll, marshaled on dll-boundary in "c" api, packaged exceptions on client-code side, , rethrown.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -