我包含了一个C ++和一个自定义的execption类,如问题的答案中所述:How do I propagate C++ exceptions to Python in a SWIG wrapper library?
在Python中使用我的类,调用抛出异常并捕获异常的函数会产生以下错误:
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
这是我的C ++类头,包括异常:
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);
};
我的SWIG标题:
%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
%}
Header&#34; Cow.i&#34;是&#34;标准&#34; SWIG-部首:
%module Cow
%{
#include "_Cow.h"
#include "Cow.h"
%}
%include "Cow.h"