我有一个问题,我所有处理字符串的 SWIG 包装器都崩溃了8 有效。
在我的代码方面,我已经解决了将输入解析为宽字符串并将它们转换为 UTF-8 的问题,但是我想用异常而不是崩溃来捕捉这些错误,不应该 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* 上,没有任何区别。
谢谢指教!