swig c to python:抛出一个中止的实例后终止

SWIG C++ to Python: terminate called after throwing an instance of ... Aborted

本文关键字:一个 终止 实例 python to swig      更新时间:2023-10-16

我正在尝试编写一个SWIG模块,我似乎无法弄清楚如何从C 中捕获异常并将它们传播到Python。这是我的代码的简化版本:

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

示例.h:

class LooperValueError {}; 
class Looper {
    private:
        int nframes;
    public:
        Looper();
        void set_nframes(int);
        int get_nframes(void);
};

示例.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)时,我没有像我期望的那样获得价值。相反,代码解释器崩溃了:

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"

我进行了调整的另一个小点:通常,您应该宁愿通过const引用而不是通过值来捕获异常。

相关文章: