Commit 4f450d14 authored by David Gobbi's avatar David Gobbi
Browse files

For Py3k, return bytes for non-utf8 C++ strings.

If a wrapped C++ method returns std::string or "const char *", the
wrappers try to decode it as utf-8 in order to return a unicode str()
in Python 3.  Originally, this meant that any decoding error led to
a UnicodeDecodeError exception.  After this change, if decoding utf-8
fails, the C++ string is returned as a raw bytes() object.
parent 175a4c43
......@@ -419,6 +419,7 @@ public:
// Description:
// Build a string return value.
static PyObject *BuildValue(const char *v, size_t l);
static PyObject *BuildValue(const char *v);
static PyObject *BuildValue(const std::string &v);
static PyObject *BuildValue(const vtkUnicodeString &v);
......@@ -707,17 +708,31 @@ PyObject *vtkPythonArgs::BuildValue(const void *a)
}
inline
PyObject *vtkPythonArgs::BuildValue(const char *a)
PyObject *vtkPythonArgs::BuildValue(const char *a, size_t l)
{
if (a)
{
#if PY_VERSION_HEX < 0x03000000
return PyString_FromStringAndSize(a, static_cast<Py_ssize_t>(l));
#else
#if PY_VERSION_HEX >= 0x03030000
return PyUnicode_FromString(a);
#elif PY_VERSION_HEX >= 0x03000000
return PyUnicode_Decode(a, static_cast<Py_ssize_t>(strlen(a)), NULL, NULL);
PyObject *o = PyUnicode_FromStringAndSize(a, static_cast<Py_ssize_t>(l));
#else
return PyString_FromString(a);
PyObject *o = PyUnicode_Decode(a, static_cast<Py_ssize_t>(l), NULL, NULL);
#endif
if (o == NULL)
{
PyErr_Clear();
o = PyBytes_FromStringAndSize(a, static_cast<Py_ssize_t>(l));
}
return o;
#endif
}
inline
PyObject *vtkPythonArgs::BuildValue(const char *a)
{
if (a)
{
return vtkPythonArgs::BuildValue(a, strlen(a));
}
Py_INCREF(Py_None);
return Py_None;
......@@ -726,13 +741,7 @@ PyObject *vtkPythonArgs::BuildValue(const char *a)
inline
PyObject *vtkPythonArgs::BuildValue(const std::string &a)
{
#if PY_VERSION_HEX >= 0x03030000
return PyUnicode_FromStringAndSize(a.c_str(), static_cast<Py_ssize_t>(a.size()));
#elif PY_VERSION_HEX >= 0x03000000
return PyUnicode_Decode(a.c_str(), static_cast<Py_ssize_t>(a.size()), NULL, NULL);
#else
return PyString_FromStringAndSize(a.c_str(), static_cast<Py_ssize_t>(a.size()));
#endif
return vtkPythonArgs::BuildValue(a.data(), a.size());
}
inline
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment