python: raise instead of crashing on strings that can't be encoded as UTF-8

getUnicodeString passed the result of PyUnicode_AsUTF8String to
PyBytes_Check without a NULL check. For a str with a lone surrogate
(for example '\udcff') the encoder fails and returns NULL, so passing such
a string to any std::string argument (putText, getTextSize, ...) crashed
the interpreter. It now returns false with the UnicodeEncodeError set,
which the converters already report.

Prepared with AI assistance (Claude Code); I reviewed the change and the verification results.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kari Pikkarainen
2026-12-01 09:12:48 -08:00
parent 395a67b1b7
commit ec2101a1a1
2 changed files with 17 additions and 1 deletions

View File

@@ -72,8 +72,9 @@ static inline bool getUnicodeString(PyObject * obj, std::string &str)
bool res = false;
if (PyUnicode_Check(obj))
{
// NULL with UnicodeEncodeError set, e.g. for a lone surrogate
PyObject * bytes = PyUnicode_AsUTF8String(obj);
if (PyBytes_Check(bytes))
if (bytes && PyBytes_Check(bytes))
{
const char * raw = PyBytes_AsString(bytes);
if (raw)