1

I wrapped a C++ and a custom execption class as described in the answer to question: How do I propagate C++ exceptions to Python in a SWIG wrapper library?
Using my class in Python, calling the function which throws the exception and catching the exception yields the following error:

Traceback (most recent call last):
    File "../WrapperTester/src/main.py", line 17, in <module>
        ret = cow.milkCow()
    File "..\WrapperTester\src\CowLib\CowLib.py", line 115, in milkCow
        return _CowLib.Cow_milkCow(self)
src.CowLib.CowLib.CowException: None

This is my C++ class header including the exception:

class CowException {
private:
    std::string message = "";
public:
    CowException(std::string msg);
    ~CowException() {};
    std::string what();
};

class _Cow
{
private:
    int milk;
    int hunger;

public:
    _Cow();
    ~_Cow();

    int milkCow() throw(CowException);
    void feed(int food) throw(CowException);
};

And my SWIG header:

%module CowLib

%include "exception.i"
%include "Cow.i"

%{
#define SWIG_FILE_WITH_INIT
#include "Cow.h"
#include "_Cow.h"
static PyObject* pCowException;
%}

%init %{
    pCowException = PyErr_NewException("_CowLib.CowException", NULL, NULL);
    Py_INCREF(pCowException);
    PyModule_AddObject(m, "CowException", pCowException);
%}

%exception Cow::milkCow {
    try {
        $action
    } catch (CowException &e) {
        PyErr_SetString(pCowException, e.what().c_str());
        SWIG_fail;
    }
}

%exception Cow::feed {
    try {
        $action
    } catch (CowException &e) {
        PyErr_SetString(pCowException, e.what().c_str());
        SWIG_fail;
    }
}

%include "_Cow.h"

%pythoncode %{
   CowException = _CowLib.CowException
%}

Where the Header "Cow.i" is the "standard" SWIG-Header:

%module Cow

%{
#include "_Cow.h"
#include "Cow.h"
%}

%include "Cow.h"
Paloghas
  • 21
  • 3
  • This is pretty close to a perfect [MCVE] - I'm struggling to unpick the difference between Cow.h and _Cow.h though. I have a few theories about what's breaking here, but I can't prove it or explain it without reproducing more precisely the same thing as you. – Flexo May 12 '18 at 16:53
  • @Flexo: The example above itself is extracted from more complex classes. Cow.h contains a wrapper class Cow of _Cow just calling the methods of _Cow. This way I wanted to minimize the dependencies of the class wrapped by SWIG. – Paloghas May 16 '18 at 12:02
  • Can you reduce the complexity down to something small and self-contained that shows the problem? I spent 20 minutes trying to answer this, but am no closer to doing so because I had to guess so much. I can't even be sure what version of swig and python you're using. – Flexo May 16 '18 at 17:08

0 Answers0