diff options
author | Tim Stumbaugh <anabus.maximus@gmail.com> | 2023-05-09 08:04:20 -0600 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-05-09 07:04:20 -0700 |
commit | cca4c51ca463ea02fa504331ff21bc313c80c7f3 (patch) | |
tree | 0a9825fe5f3232e09a1392dcabfc350ae489b842 | |
parent | e9b961d9b913575c07ba28c038c3706731768da6 (diff) | |
download | pybind11-cca4c51ca463ea02fa504331ff21bc313c80c7f3.tar.gz |
Update errors in string "Explicit conversions" docs (#4658)
`PyUnicode_DecodeLatin1` requires you to pass in the `error`
parameter. The code as it is in the docs didn't compile.
There is a reference leak in the example
code. `PyUnicode_DecodeLatin1` returns a new reference. Calling
`py::str(PyObject*)` calls `PyObject_Str`, which also returns a new
reference. That reference is managed by the `py::str`
constructor (which correctly steals the reference, using the
`stolen_t` constructor), but the original reference returned by
`PyUnicode_DecodeLatin1` is never decref'd: it never makes it into an
`object`, and it's never manually decremented.
This fixes both of those issues. The code compiles, and I viewed the
sphinx docs locally.
-rw-r--r-- | docs/advanced/cast/strings.rst | 10 |
1 files changed, 7 insertions, 3 deletions
diff --git a/docs/advanced/cast/strings.rst b/docs/advanced/cast/strings.rst index e246c521..271716b4 100644 --- a/docs/advanced/cast/strings.rst +++ b/docs/advanced/cast/strings.rst @@ -101,8 +101,11 @@ conversion has the same overhead as implicit conversion. m.def("str_output", []() { std::string s = "Send your r\xe9sum\xe9 to Alice in HR"; // Latin-1 - py::str py_s = PyUnicode_DecodeLatin1(s.data(), s.length()); - return py_s; + py::handle py_s = PyUnicode_DecodeLatin1(s.data(), s.length(), nullptr); + if (!py_s) { + throw py::error_already_set(); + } + return py::reinterpret_steal<py::str>(py_s); } ); @@ -113,7 +116,8 @@ conversion has the same overhead as implicit conversion. The `Python C API <https://docs.python.org/3/c-api/unicode.html#built-in-codecs>`_ provides -several built-in codecs. +several built-in codecs. Note that these all return *new* references, so +use :cpp:func:`reinterpret_steal` when converting them to a :cpp:class:`str`. One could also use a third party encoding library such as libiconv to transcode |