SWIG C++;to Python:在抛出。。。流产 我试图编写一个SWIG模块,我似乎无法找出如何从C++捕获异常并将其传播到Python。以下是我的代码的简化版本:

SWIG C++;to Python:在抛出。。。流产 我试图编写一个SWIG模块,我似乎无法找出如何从C++捕获异常并将其传播到Python。以下是我的代码的简化版本:,python,c++,swig,Python,C++,Swig,示例.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; } 例一

示例.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;

}
例一:

%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\n框架(-2)时,我并没有得到预期的ValueError;相反,代码解释器会崩溃:

terminate called after throwing an instance of 'LooperValueError'
Aborted

似乎这个异常没有被包装器捕获。我做错了什么?

异常
%exception
的影响仅对它后面的声明是局部的。您在
%include
之后编写了
%exception
,因此它实际上不会应用于任何内容。(查看生成的代码以验证这一点-您的try/catch块实际上还没有到达输出)

因此,您的界面应该如下所示:

%module example
%{
#include "example.h"
%}

%exception {
    try {
        $function
    } catch (const LooperValueError&) {
        PyErr_SetString(PyExc_ValueError,"Looper value out of range");
        return NULL;
    }   
}

%include "example.h"
我又调整了一个小问题:通常你应该更喜欢按值而不是按值

%module example
%{
#include "example.h"
%}

%exception {
    try {
        $function
    } catch (const LooperValueError&) {
        PyErr_SetString(PyExc_ValueError,"Looper value out of range");
        return NULL;
    }   
}

%include "example.h"