I have a library in C++ where I have my own exception class called "Exception" and I use SWIG to create a wrapper for Python. The idea is that the exception is catched and its methods can be used like in this example:
example.py:
try:
functionThatThrowsError()
except myLibrary.Exception as exc:
print (exc.code(), exc.msg())
The wrapper for the exception is created without problem, the thing is that Python requires that user-made exceptions inherit from the Python builtin BaseException class and inspecting myLibrary.py generated it shows that the class is not inheriting from BaseException but from object. If I manually change that line to inherit from BaseException instead of object the example.py works perfectly.
My question is how to tell SWIG that my Exception class should inherit from the BaseException class from Python.
Here are the other files to give more context:
exception.h:
#ifndef EXCEPTION
#define EXCEPTION
#include <string.h>
#include<exception>
using namespace std;
class Exception : public exception {
public:
Exception(int c, const char* m);
const char* msg();
const int code();
virtual const char* what() const throw();
~Exception() {};
int _code; //!< Error code.
char _msg[256]; //! Error message.
};
#endif
exception.cpp:
#include "../include/Exception.h"
Exception::Exception(int c, const char* m)
{
_code = c;
strncpy(_msg, m, 256);
}
const char* Exception::msg()
{
return _msg;
}
const int Exception::code()
{
return _code;
}
const char* Exception::what() const throw()
{
return _msg;
}
myLibrary.i:
%module myLibrary
%{
#define SWIG_FILE_WITH_INIT
#include "../include/Exception.h"
%}
%include "stl.i"
%exception {
try {
$action
} catch (Exception &e) {
SWIG_Python_Raise(SWIG_NewPointerObj(
(new Exception(e.code(), e.msg())),
SWIGTYPE_p_Exception,SWIG_POINTER_OWN),
"Exception", SWIGTYPE_p_Exception);
SWIG_fail;
} catch (...) {
SWIG_exception(SWIG_RuntimeError, "unknown exception");
}
}
%include "../include/Exception.h"
%inline %{
// The -builtin SWIG option results in SWIGPYTHON_BUILTIN being defined
#ifdef SWIGPYTHON_BUILTIN
bool is_python_builtin() { return true; }
#else
bool is_python_builtin() { return false; }
#endif
%}