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

问题描述 投票:-1回答:2

我有一个问题,我处理字符串的所有SWIG包装器崩溃如果我在std :: string中传递一个错误的编码字符串,我的意思是包含èé等字符串,字符对当前语言环境有效,但不是UTF- 8有效。

在我的代码方面,我已经解决了将输入解析为宽字符串并将它们转换为UTF-8的问题,但是我想用异常而不是崩溃来捕获那些错误,不应该认为PyUnicode_Check失败了这些字符串?

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中。我注意到字符串作为std :: string传递,但也发生在const char *中,没有任何区别。

谢谢你的建议!

unicode utf-8 swig stdstring
2个回答
0
投票

无法重现。如果此示例无法解决您的问题并需要进一步的帮助,请编辑您的问题并添加Minimal, Complete, Verifable Example

test.i

%module test

%include <std_string.i>

%inline %{
#include <string>

std::string func(std::string s)
{
    return '[' + s + ']';
}
%}

演示:

Python 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:35:05) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.func('ábc')
'[ábc]'

0
投票

问题出在我们仍在使用的3.3.0版本,更新到3.3.7解决了问题,在Python发行说明中有关于PyUnicode_Check修复了几个错误

© www.soinside.com 2019 - 2024. All rights reserved.