Commit 8373f74b authored by Alejandro Homs Puron's avatar Alejandro Homs Puron Committed by operator for beamline

SIP: fix PyString/Unicode vs. std::string conversion

parent 08e912a3
This diff is collapsed.
This diff is collapsed.
......@@ -35,22 +35,59 @@ void @PROJECT_NAME_LOWER@_import_array();
}
%End
%UnitCode
#include <Python.h>
#if !defined(LIMA_REPR_CODE)
%ModuleHeaderCode
#include "lima/SoftOpId.h"
inline PyObject *sipConvertToPyStr(const std::string& s)
{
PyObject *newstring;
#if PY_MAJOR_VERSION >= 3
#define LIMA_REPR_CODE \
std::ostringstream str; \
str << *sipCpp; \
const std::string& tmpString = str.str(); \
sipRes = PyUnicode_FromString(tmpString.c_str());
// convert an std::string to a Python (unicode) string
newstring = PyUnicode_DecodeUTF8(s.c_str(), s.length(), NULL);
if (newstring == NULL) {
PyErr_Clear();
newstring = PyString_FromString(s.c_str());
}
#else
// convert an std::string to a Python string - assume an ASCII string
newstring = PyString_FromString(s.c_str());
#endif
return newstring;
}
inline bool sipCheckConvertFromPyStr(PyObject *sipPy)
{
return (PyString_Check(sipPy) || PyUnicode_Check(sipPy));
}
inline std::string sipConvertFromPyStr(PyObject *sipPy)
{
std::string s;
// Allow a Python string (or a unicode string) whenever a string is
// expected.
// If argument is a Unicode string, just decode it to UTF-8
// If argument is a Python string, assume it's UTF-8
if (PyUnicode_Check(sipPy)) {
PyObject *pyS = PyUnicode_AsEncodedString(sipPy, "UTF-8", "");
s = PyString_AS_STRING(pyS);
Py_DECREF(pyS);
} else if (PyString_Check(sipPy)) {
s = PyString_AS_STRING(sipPy);
} else if (sipPy != Py_None) {
throw std::exception();
}
return s;
}
%End
%UnitCode
#if !defined(LIMA_REPR_CODE)
#define LIMA_REPR_CODE \
std::ostringstream str; \
str << *sipCpp; \
const std::string& tmpString = str.str(); \
sipRes = PyString_FromString(tmpString.c_str());
#endif // PY_MAJOR_VERSION
sipRes = sipConvertToPyStr(str.str());
#endif // !defined(LIMA_REPR_CODE)
%End
......
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