SWIG类型映射中的C++异常 我试图用C++来包装一些简单的C++,当试图包装最基本的东西时遇到了问题。

SWIG类型映射中的C++异常 我试图用C++来包装一些简单的C++,当试图包装最基本的东西时遇到了问题。,c++,swig,C++,Swig,SWIG似乎并没有试图捕捉类型映射中可能发生的异常 例如,对于以下SIWG接口文件: %module badswig std::string func(); SWIG生成以下内容: SWIGINTERN PyObject *_wrap_func(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; std::string result; if (!PyArg_ParseTuple(a

SWIG似乎并没有试图捕捉类型映射中可能发生的异常

例如,对于以下SIWG接口文件:

%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;
}
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;
}
生成以下内容:

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

注意新的std::string没有try-catch。typemap只是告诉SWIG要生成什么接口代码来转换调用参数和函数的返回值。%Exchange在要包装的函数之前和之后生成代码,将异常从C++转换为目标语言,或者将C++异常转换为等效的目标语言。如果使用SWIG文档中的%Exchange,则应该发现您的包装器函数包含为该函数指定的Type MeMAP代码,以及您的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
}

没错,那么我们如何在与类型映射相关的代码中获得异常处理呢?除了在所有类型映射中放置try/catch块之外,您是否找到了一个很好的解决方案?