Make it possible to customize swig_check() definition

Move this function definition to cexcept.swg from the code and only
define it if SWIG_swig_check_DEFINED is not defined yet, which both
simplifies the code in C.cxx and makes exception handling code more
flexible, as it's now possible to predefine SWIG_swig_check_DEFINED
in the code injected into the "cxxheader" section to replace the default
implementation. Show an example of doing this in the documentation and
document handling exceptions with C API too.

The changes above required adding a new "cxxcode" section, corresponding
to the "implementation" part of C++ wrappers and defining a new
SWIG_CXX_WRAPPERS preprocessor symbol to allow only adding C++-specific
code when C++ wrappers are actually generated. Also improve the
documentation of the C-specific sections in the manual.
This commit is contained in:
Vadim Zeitlin 2021-12-09 00:18:05 +01:00
commit f06bba320a
3 changed files with 86 additions and 22 deletions

View file

@ -62,6 +62,39 @@ SWIGEXPORTC void SWIG_CException_Raise(int code, const char* msg) {
#endif // SWIG_CException_DEFINED
%}
#ifdef SWIG_CXX_WRAPPERS
// This is somewhat of a hack, but our generated header may include another
// generated header, when using multiple modules, and defining swig_check() in
// all of them would result in errors, so we use SWIG_swig_check_DEFINED to
// prevent this from happening.
//
// This also has a nice side effect of allowing the user code to predefine this
// symbol and provide their own SWIG_swig_check_DEFINED implementation to
// customize exception handling.
%insert("cxxcode") %{
#ifndef SWIG_swig_check_DEFINED
#define SWIG_swig_check_DEFINED 1
inline void swig_check() {
if (SWIG_CException* swig_ex = SWIG_CException::get_pending()) {
SWIG_CException swig_ex_copy{*swig_ex};
delete swig_ex;
SWIG_CException::reset_pending();
throw swig_ex_copy;
}
}
template <typename T> T swig_check(T x) {
swig_check();
return x;
}
#endif // SWIG_swig_check_DEFINED
%}
#endif // SWIG_CXX_WRAPPERS
%insert("runtime") "swigerrors.swg"
#define SWIG_exception(code, msg)\