Py学习  »  Python

SWIG错误编码的字符串导致Python崩溃

Leonardo Bernardini • 5 年前 • 1763 次点击  

在我的代码方面,我已经解决了将输入解析为宽字符串并将其转换为UTF-8的问题,但是我希望捕获这些类型的错误,而不是捕获崩溃,难道PyUnicode检查不应该失败吗?

Swig在调用PyString_AsStringAndSize()时实际在Swig_AsCharPtrAndSize()中崩溃,这是Swig生成的代码:

    SWIGINTERN int
SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc)
{
#if PY_VERSION_HEX>=0x03000000
#if defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
  if (PyBytes_Check(obj))
#else
  if (PyUnicode_Check(obj))
#endif
#else  
  if (PyString_Check(obj))
#endif
  {
    char *cstr; Py_ssize_t len;
#if PY_VERSION_HEX>=0x03000000
#if !defined(SWIG_PYTHON_STRICT_BYTE_CHAR)
    if (!alloc && cptr) {
        /* We can't allow converting without allocation, since the internal
           representation of string in Python 3 is UCS-2/UCS-4 but we require
           a UTF-8 representation.
           TODO(bhy) More detailed explanation */
        return SWIG_RuntimeError;
    }
    obj = PyUnicode_AsUTF8String(obj);
    if(alloc) *alloc = SWIG_NEWOBJ;
#endif
    PyBytes_AsStringAndSize(obj, &cstr, &len);
#else
    PyString_AsStringAndSize(obj, &cstr, &len);
#endif
    if (cptr) {

崩溃恰好进入最后一个可见的PyString_AsStringAndSize。

谢谢你的建议!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53858
 
1763 次点击  
文章 [ 2 ]  |  最新文章 5 年前