Back to home page

EIC code displayed by LXR

 
 

    


Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/advanced/cast/strings.rst is written in an unsupported language. File is not indexed.

0001 Strings, bytes and Unicode conversions
0002 ######################################
0003 
0004 Passing Python strings to C++
0005 =============================
0006 
0007 When a Python ``str`` is passed from Python to a C++ function that accepts
0008 ``std::string`` or ``char *`` as arguments, pybind11 will encode the Python
0009 string to UTF-8. All Python ``str`` can be encoded in UTF-8, so this operation
0010 does not fail.
0011 
0012 The C++ language is encoding agnostic. It is the responsibility of the
0013 programmer to track encodings. It's often easiest to simply `use UTF-8
0014 everywhere <http://utf8everywhere.org/>`_.
0015 
0016 .. code-block:: c++
0017 
0018     m.def("utf8_test",
0019         [](const std::string &s) {
0020             cout << "utf-8 is icing on the cake.\n";
0021             cout << s;
0022         }
0023     );
0024     m.def("utf8_charptr",
0025         [](const char *s) {
0026             cout << "My favorite food is\n";
0027             cout << s;
0028         }
0029     );
0030 
0031 .. code-block:: pycon
0032 
0033     >>> utf8_test("🎂")
0034     utf-8 is icing on the cake.
0035     🎂
0036 
0037     >>> utf8_charptr("🍕")
0038     My favorite food is
0039     🍕
0040 
0041 .. note::
0042 
0043     Some terminal emulators do not support UTF-8 or emoji fonts and may not
0044     display the example above correctly.
0045 
0046 The results are the same whether the C++ function accepts arguments by value or
0047 reference, and whether or not ``const`` is used.
0048 
0049 Passing bytes to C++
0050 --------------------
0051 
0052 A Python ``bytes`` object will be passed to C++ functions that accept
0053 ``std::string`` or ``char*`` *without* conversion.  In order to make a function
0054 *only* accept ``bytes`` (and not ``str``), declare it as taking a ``py::bytes``
0055 argument.
0056 
0057 
0058 Returning C++ strings to Python
0059 ===============================
0060 
0061 When a C++ function returns a ``std::string`` or ``char*`` to a Python caller,
0062 **pybind11 will assume that the string is valid UTF-8** and will decode it to a
0063 native Python ``str``, using the same API as Python uses to perform
0064 ``bytes.decode('utf-8')``. If this implicit conversion fails, pybind11 will
0065 raise a ``UnicodeDecodeError``.
0066 
0067 .. code-block:: c++
0068 
0069     m.def("std_string_return",
0070         []() {
0071             return std::string("This string needs to be UTF-8 encoded");
0072         }
0073     );
0074 
0075 .. code-block:: pycon
0076 
0077     >>> isinstance(example.std_string_return(), str)
0078     True
0079 
0080 
0081 Because UTF-8 is inclusive of pure ASCII, there is never any issue with
0082 returning a pure ASCII string to Python. If there is any possibility that the
0083 string is not pure ASCII, it is necessary to ensure the encoding is valid
0084 UTF-8.
0085 
0086 .. warning::
0087 
0088     Implicit conversion assumes that a returned ``char *`` is null-terminated.
0089     If there is no null terminator a buffer overrun will occur.
0090 
0091 Explicit conversions
0092 --------------------
0093 
0094 If some C++ code constructs a ``std::string`` that is not a UTF-8 string, one
0095 can perform a explicit conversion and return a ``py::str`` object. Explicit
0096 conversion has the same overhead as implicit conversion.
0097 
0098 .. code-block:: c++
0099 
0100     // This uses the Python C API to convert Latin-1 to Unicode
0101     m.def("str_output",
0102         []() {
0103             std::string s = "Send your r\xe9sum\xe9 to Alice in HR"; // Latin-1
0104             py::str py_s = PyUnicode_DecodeLatin1(s.data(), s.length());
0105             return py_s;
0106         }
0107     );
0108 
0109 .. code-block:: pycon
0110 
0111     >>> str_output()
0112     'Send your résumé to Alice in HR'
0113 
0114 The `Python C API
0115 <https://docs.python.org/3/c-api/unicode.html#built-in-codecs>`_ provides
0116 several built-in codecs.
0117 
0118 
0119 One could also use a third party encoding library such as libiconv to transcode
0120 to UTF-8.
0121 
0122 Return C++ strings without conversion
0123 -------------------------------------
0124 
0125 If the data in a C++ ``std::string`` does not represent text and should be
0126 returned to Python as ``bytes``, then one can return the data as a
0127 ``py::bytes`` object.
0128 
0129 .. code-block:: c++
0130 
0131     m.def("return_bytes",
0132         []() {
0133             std::string s("\xba\xd0\xba\xd0");  // Not valid UTF-8
0134             return py::bytes(s);  // Return the data without transcoding
0135         }
0136     );
0137 
0138 .. code-block:: pycon
0139 
0140     >>> example.return_bytes()
0141     b'\xba\xd0\xba\xd0'
0142 
0143 
0144 Note the asymmetry: pybind11 will convert ``bytes`` to ``std::string`` without
0145 encoding, but cannot convert ``std::string`` back to ``bytes`` implicitly.
0146 
0147 .. code-block:: c++
0148 
0149     m.def("asymmetry",
0150         [](std::string s) {  // Accepts str or bytes from Python
0151             return s;  // Looks harmless, but implicitly converts to str
0152         }
0153     );
0154 
0155 .. code-block:: pycon
0156 
0157     >>> isinstance(example.asymmetry(b"have some bytes"), str)
0158     True
0159 
0160     >>> example.asymmetry(b"\xba\xd0\xba\xd0")  # invalid utf-8 as bytes
0161     UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 0: invalid start byte
0162 
0163 
0164 Wide character strings
0165 ======================
0166 
0167 When a Python ``str`` is passed to a C++ function expecting ``std::wstring``,
0168 ``wchar_t*``, ``std::u16string`` or ``std::u32string``, the ``str`` will be
0169 encoded to UTF-16 or UTF-32 depending on how the C++ compiler implements each
0170 type, in the platform's native endianness. When strings of these types are
0171 returned, they are assumed to contain valid UTF-16 or UTF-32, and will be
0172 decoded to Python ``str``.
0173 
0174 .. code-block:: c++
0175 
0176     #define UNICODE
0177     #include <windows.h>
0178 
0179     m.def("set_window_text",
0180         [](HWND hwnd, std::wstring s) {
0181             // Call SetWindowText with null-terminated UTF-16 string
0182             ::SetWindowText(hwnd, s.c_str());
0183         }
0184     );
0185     m.def("get_window_text",
0186         [](HWND hwnd) {
0187             const int buffer_size = ::GetWindowTextLength(hwnd) + 1;
0188             auto buffer = std::make_unique< wchar_t[] >(buffer_size);
0189 
0190             ::GetWindowText(hwnd, buffer.data(), buffer_size);
0191 
0192             std::wstring text(buffer.get());
0193 
0194             // wstring will be converted to Python str
0195             return text;
0196         }
0197     );
0198 
0199 Strings in multibyte encodings such as Shift-JIS must transcoded to a
0200 UTF-8/16/32 before being returned to Python.
0201 
0202 
0203 Character literals
0204 ==================
0205 
0206 C++ functions that accept character literals as input will receive the first
0207 character of a Python ``str`` as their input. If the string is longer than one
0208 Unicode character, trailing characters will be ignored.
0209 
0210 When a character literal is returned from C++ (such as a ``char`` or a
0211 ``wchar_t``), it will be converted to a ``str`` that represents the single
0212 character.
0213 
0214 .. code-block:: c++
0215 
0216     m.def("pass_char", [](char c) { return c; });
0217     m.def("pass_wchar", [](wchar_t w) { return w; });
0218 
0219 .. code-block:: pycon
0220 
0221     >>> example.pass_char("A")
0222     'A'
0223 
0224 While C++ will cast integers to character types (``char c = 0x65;``), pybind11
0225 does not convert Python integers to characters implicitly. The Python function
0226 ``chr()`` can be used to convert integers to characters.
0227 
0228 .. code-block:: pycon
0229 
0230     >>> example.pass_char(0x65)
0231     TypeError
0232 
0233     >>> example.pass_char(chr(0x65))
0234     'A'
0235 
0236 If the desire is to work with an 8-bit integer, use ``int8_t`` or ``uint8_t``
0237 as the argument type.
0238 
0239 Grapheme clusters
0240 -----------------
0241 
0242 A single grapheme may be represented by two or more Unicode characters. For
0243 example 'é' is usually represented as U+00E9 but can also be expressed as the
0244 combining character sequence U+0065 U+0301 (that is, the letter 'e' followed by
0245 a combining acute accent). The combining character will be lost if the
0246 two-character sequence is passed as an argument, even though it renders as a
0247 single grapheme.
0248 
0249 .. code-block:: pycon
0250 
0251     >>> example.pass_wchar("é")
0252     'é'
0253 
0254     >>> combining_e_acute = "e" + "\u0301"
0255 
0256     >>> combining_e_acute
0257     'é'
0258 
0259     >>> combining_e_acute == "é"
0260     False
0261 
0262     >>> example.pass_wchar(combining_e_acute)
0263     'e'
0264 
0265 Normalizing combining characters before passing the character literal to C++
0266 may resolve *some* of these issues:
0267 
0268 .. code-block:: pycon
0269 
0270     >>> example.pass_wchar(unicodedata.normalize("NFC", combining_e_acute))
0271     'é'
0272 
0273 In some languages (Thai for example), there are `graphemes that cannot be
0274 expressed as a single Unicode code point
0275 <http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries>`_, so there is
0276 no way to capture them in a C++ character type.
0277 
0278 
0279 C++17 string views
0280 ==================
0281 
0282 C++17 string views are automatically supported when compiling in C++17 mode.
0283 They follow the same rules for encoding and decoding as the corresponding STL
0284 string type (for example, a ``std::u16string_view`` argument will be passed
0285 UTF-16-encoded data, and a returned ``std::string_view`` will be decoded as
0286 UTF-8).
0287 
0288 References
0289 ==========
0290 
0291 * `The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) <https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/>`_
0292 * `C++ - Using STL Strings at Win32 API Boundaries <https://msdn.microsoft.com/en-ca/magazine/mt238407.aspx>`_