SWIG:包中的C++异常在Python中不产生任何异常

2024-04-25 05:14:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我封装了C++和自定义的执行类,如在回答问题中所描述的:How do I propagate C++ exceptions to Python in a SWIG wrapper library?
在Python中使用my class,调用引发异常的函数并捕获异常会产生以下错误:

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);
};

还有我的泳衣头:

%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
%}

其中标题“Cow.i”是“标准”SWIG标题:

%module Cow

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

%include "Cow.h"

Tags: insrcstringincludewhatclassswigint