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

时间:2019-04-11 10:18:50

标签: unicode utf-8 swig stdstring

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

在代码方面,我已经解决了将输入解析为宽字符串并将其转换为UTF-8的问题,但是我想使用Exception而不是当机的方式捕获此类错误,因此PyUnicode_Check不应该失败用那些字符串?

在调用PyString_AsStringAndSize()时,Swig实际上在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 *也是如此,没有任何区别。

多谢指教!

2 个答案:

答案 0 :(得分: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]'

答案 1 :(得分:0)

问题是我们仍在使用的3.3.0版本,更新为3.3.7解决了该问题,在Python发行说明中,已修复了一些有关PyUnicode_Check的错误

相关问题