SWIG类型映射中的c++异常
C++ Exceptions in SWIG typemaps
我试图用c++来包装一些简单的c++,在尝试包装最基本的东西时遇到了一个问题。
SWIG似乎没有尝试捕获可能发生在typemap内部的异常。
例如:
%module badswig
std::string func();
SWIG生成这个:
SWIGINTERN PyObject *_wrap_func(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
std::string result;
if (!PyArg_ParseTuple(args,(char *)":func")) SWIG_fail;
result = func();
resultobj = SWIG_NewPointerObj((new std::string(static_cast< const std::string& >(result))), SWIGTYPE_p_std__string, SWIG_POINTER_OWN | 0 );
return resultobj;
fail:
return NULL;
}
注意new std::string
是完全不受保护的,所以如果std::bad_alloc
被抛出,它将传播到Python并崩溃。
除了SWIG使用new
之外,可能还有其他情况。
有%exception
处理这个包装函数(如果func()
抛出),但我找不到任何东西来处理这个类型映射,特别是由SWIG提供的。
我错过了什么吗?有什么方法可以正确处理这个问题吗?
编辑:
为了回答和澄清我的问题,%exception
没有达到我想要的:
%module badswig
%exception %{
try {
$action
} catch (const std::bad_alloc&) {
PyErr_NoMemory();
SWIG_fail;
}
%}
std::string func();
生成:
SWIGINTERN PyObject *_wrap_func(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
std::string result;
if (!PyArg_ParseTuple(args,(char *)":func")) SWIG_fail;
try {
result = func();
} catch (const std::bad_alloc&) {
PyErr_NoMemory();
SWIG_fail;
}
resultobj = SWIG_NewPointerObj((new std::string(static_cast< const std::string& >(result))), SWIGTYPE_p_std__string, SWIG_POINTER_OWN | 0 );
return resultobj;
fail:
return NULL;
}
注意new std::string
周围没有try catch
typemap只是告诉SWIG要生成什么接口代码来转换函数的调用参数和返回值。%exception
在要包装的函数之前和之后立即生成代码,以将异常从c++转换为目标语言,或者将c++异常转换为等效的目标语言。如果按照SWIG文档使用%exception
,您应该发现包装器函数包含为该函数指定的typemap代码,以及c++函数周围的异常代码:
void swig_function(PyObj*) {
typemap-related code to convert args from Python to C++
exception-related code
your-c++-func(args)
exception-related code (catch clauses etc)
typemap-related code to convert return value from C++ to Python
}
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- Pytorch torch.cholesky忽略异常