【发布时间】:2017-02-21 16:10:58
【问题描述】:
我正在尝试编写一个 SWIG 模块,但我似乎无法弄清楚如何从 C++ 捕获异常并将它们传播到 Python。这是我的代码的简化版本:
example.cpp:
#include "example.h"
Looper::Looper() {
nframes = 0;
}
void Looper::set_nframes(int nf) {
if (nf < 0) {
throw LooperValueError();
}
nframes = nf;
}
int Looper::get_nframes(void) {
return nframes;
}
example.h:
class LooperValueError {};
class Looper {
private:
int nframes;
public:
Looper();
void set_nframes(int);
int get_nframes(void);
};
example.i:
%module example
%{
#include "example.h"
%}
%include "example.h"
%exception {
try {
$function
} catch (LooperValueError) {
PyErr_SetString(PyExc_ValueError,"Looper value out of range");
return NULL;
}
}
这构建得很好。但是在 Python 中,当我调用 Looper.set_nframes(-2) 时,并没有像我期望的那样得到 ValueError;而是代码解释器崩溃:
terminate called after throwing an instance of 'LooperValueError'
Aborted
似乎异常没有被包装器捕获。我做错了什么?
【问题讨论】: