strings.rst 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. Strings, bytes and Unicode conversions
  2. ######################################
  3. .. note::
  4. This section discusses string handling in terms of Python 3 strings. For
  5. Python 2.7, replace all occurrences of ``str`` with ``unicode`` and
  6. ``bytes`` with ``str``. Python 2.7 users may find it best to use ``from
  7. __future__ import unicode_literals`` to avoid unintentionally using ``str``
  8. instead of ``unicode``.
  9. Passing Python strings to C++
  10. =============================
  11. When a Python ``str`` is passed from Python to a C++ function that accepts
  12. ``std::string`` or ``char *`` as arguments, pybind11 will encode the Python
  13. string to UTF-8. All Python ``str`` can be encoded in UTF-8, so this operation
  14. does not fail.
  15. The C++ language is encoding agnostic. It is the responsibility of the
  16. programmer to track encodings. It's often easiest to simply `use UTF-8
  17. everywhere <http://utf8everywhere.org/>`_.
  18. .. code-block:: c++
  19. m.def("utf8_test",
  20. [](const std::string &s) {
  21. cout << "utf-8 is icing on the cake.\n";
  22. cout << s;
  23. }
  24. );
  25. m.def("utf8_charptr",
  26. [](const char *s) {
  27. cout << "My favorite food is\n";
  28. cout << s;
  29. }
  30. );
  31. .. code-block:: python
  32. >>> utf8_test('🎂')
  33. utf-8 is icing on the cake.
  34. 🎂
  35. >>> utf8_charptr('🍕')
  36. My favorite food is
  37. 🍕
  38. .. note::
  39. Some terminal emulators do not support UTF-8 or emoji fonts and may not
  40. display the example above correctly.
  41. The results are the same whether the C++ function accepts arguments by value or
  42. reference, and whether or not ``const`` is used.
  43. Passing bytes to C++
  44. --------------------
  45. A Python ``bytes`` object will be passed to C++ functions that accept
  46. ``std::string`` or ``char*`` *without* conversion. On Python 3, in order to
  47. make a function *only* accept ``bytes`` (and not ``str``), declare it as taking
  48. a ``py::bytes`` argument.
  49. Returning C++ strings to Python
  50. ===============================
  51. When a C++ function returns a ``std::string`` or ``char*`` to a Python caller,
  52. **pybind11 will assume that the string is valid UTF-8** and will decode it to a
  53. native Python ``str``, using the same API as Python uses to perform
  54. ``bytes.decode('utf-8')``. If this implicit conversion fails, pybind11 will
  55. raise a ``UnicodeDecodeError``.
  56. .. code-block:: c++
  57. m.def("std_string_return",
  58. []() {
  59. return std::string("This string needs to be UTF-8 encoded");
  60. }
  61. );
  62. .. code-block:: python
  63. >>> isinstance(example.std_string_return(), str)
  64. True
  65. Because UTF-8 is inclusive of pure ASCII, there is never any issue with
  66. returning a pure ASCII string to Python. If there is any possibility that the
  67. string is not pure ASCII, it is necessary to ensure the encoding is valid
  68. UTF-8.
  69. .. warning::
  70. Implicit conversion assumes that a returned ``char *`` is null-terminated.
  71. If there is no null terminator a buffer overrun will occur.
  72. Explicit conversions
  73. --------------------
  74. If some C++ code constructs a ``std::string`` that is not a UTF-8 string, one
  75. can perform a explicit conversion and return a ``py::str`` object. Explicit
  76. conversion has the same overhead as implicit conversion.
  77. .. code-block:: c++
  78. // This uses the Python C API to convert Latin-1 to Unicode
  79. m.def("str_output",
  80. []() {
  81. std::string s = "Send your r\xe9sum\xe9 to Alice in HR"; // Latin-1
  82. py::str py_s = PyUnicode_DecodeLatin1(s.data(), s.length());
  83. return py_s;
  84. }
  85. );
  86. .. code-block:: python
  87. >>> str_output()
  88. 'Send your résumé to Alice in HR'
  89. The `Python C API
  90. <https://docs.python.org/3/c-api/unicode.html#built-in-codecs>`_ provides
  91. several built-in codecs.
  92. One could also use a third party encoding library such as libiconv to transcode
  93. to UTF-8.
  94. Return C++ strings without conversion
  95. -------------------------------------
  96. If the data in a C++ ``std::string`` does not represent text and should be
  97. returned to Python as ``bytes``, then one can return the data as a
  98. ``py::bytes`` object.
  99. .. code-block:: c++
  100. m.def("return_bytes",
  101. []() {
  102. std::string s("\xba\xd0\xba\xd0"); // Not valid UTF-8
  103. return py::bytes(s); // Return the data without transcoding
  104. }
  105. );
  106. .. code-block:: python
  107. >>> example.return_bytes()
  108. b'\xba\xd0\xba\xd0'
  109. Note the asymmetry: pybind11 will convert ``bytes`` to ``std::string`` without
  110. encoding, but cannot convert ``std::string`` back to ``bytes`` implicitly.
  111. .. code-block:: c++
  112. m.def("asymmetry",
  113. [](std::string s) { // Accepts str or bytes from Python
  114. return s; // Looks harmless, but implicitly converts to str
  115. }
  116. );
  117. .. code-block:: python
  118. >>> isinstance(example.asymmetry(b"have some bytes"), str)
  119. True
  120. >>> example.asymmetry(b"\xba\xd0\xba\xd0") # invalid utf-8 as bytes
  121. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xba in position 0: invalid start byte
  122. Wide character strings
  123. ======================
  124. When a Python ``str`` is passed to a C++ function expecting ``std::wstring``,
  125. ``wchar_t*``, ``std::u16string`` or ``std::u32string``, the ``str`` will be
  126. encoded to UTF-16 or UTF-32 depending on how the C++ compiler implements each
  127. type, in the platform's native endianness. When strings of these types are
  128. returned, they are assumed to contain valid UTF-16 or UTF-32, and will be
  129. decoded to Python ``str``.
  130. .. code-block:: c++
  131. #define UNICODE
  132. #include <windows.h>
  133. m.def("set_window_text",
  134. [](HWND hwnd, std::wstring s) {
  135. // Call SetWindowText with null-terminated UTF-16 string
  136. ::SetWindowText(hwnd, s.c_str());
  137. }
  138. );
  139. m.def("get_window_text",
  140. [](HWND hwnd) {
  141. const int buffer_size = ::GetWindowTextLength(hwnd) + 1;
  142. auto buffer = std::make_unique< wchar_t[] >(buffer_size);
  143. ::GetWindowText(hwnd, buffer.data(), buffer_size);
  144. std::wstring text(buffer.get());
  145. // wstring will be converted to Python str
  146. return text;
  147. }
  148. );
  149. .. warning::
  150. Wide character strings may not work as described on Python 2.7 or Python
  151. 3.3 compiled with ``--enable-unicode=ucs2``.
  152. Strings in multibyte encodings such as Shift-JIS must transcoded to a
  153. UTF-8/16/32 before being returned to Python.
  154. Character literals
  155. ==================
  156. C++ functions that accept character literals as input will receive the first
  157. character of a Python ``str`` as their input. If the string is longer than one
  158. Unicode character, trailing characters will be ignored.
  159. When a character literal is returned from C++ (such as a ``char`` or a
  160. ``wchar_t``), it will be converted to a ``str`` that represents the single
  161. character.
  162. .. code-block:: c++
  163. m.def("pass_char", [](char c) { return c; });
  164. m.def("pass_wchar", [](wchar_t w) { return w; });
  165. .. code-block:: python
  166. >>> example.pass_char('A')
  167. 'A'
  168. While C++ will cast integers to character types (``char c = 0x65;``), pybind11
  169. does not convert Python integers to characters implicitly. The Python function
  170. ``chr()`` can be used to convert integers to characters.
  171. .. code-block:: python
  172. >>> example.pass_char(0x65)
  173. TypeError
  174. >>> example.pass_char(chr(0x65))
  175. 'A'
  176. If the desire is to work with an 8-bit integer, use ``int8_t`` or ``uint8_t``
  177. as the argument type.
  178. Grapheme clusters
  179. -----------------
  180. A single grapheme may be represented by two or more Unicode characters. For
  181. example 'é' is usually represented as U+00E9 but can also be expressed as the
  182. combining character sequence U+0065 U+0301 (that is, the letter 'e' followed by
  183. a combining acute accent). The combining character will be lost if the
  184. two-character sequence is passed as an argument, even though it renders as a
  185. single grapheme.
  186. .. code-block:: python
  187. >>> example.pass_wchar('é')
  188. 'é'
  189. >>> combining_e_acute = 'e' + '\u0301'
  190. >>> combining_e_acute
  191. 'é'
  192. >>> combining_e_acute == 'é'
  193. False
  194. >>> example.pass_wchar(combining_e_acute)
  195. 'e'
  196. Normalizing combining characters before passing the character literal to C++
  197. may resolve *some* of these issues:
  198. .. code-block:: python
  199. >>> example.pass_wchar(unicodedata.normalize('NFC', combining_e_acute))
  200. 'é'
  201. In some languages (Thai for example), there are `graphemes that cannot be
  202. expressed as a single Unicode code point
  203. <http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries>`_, so there is
  204. no way to capture them in a C++ character type.
  205. C++17 string views
  206. ==================
  207. C++17 string views are automatically supported when compiling in C++17 mode.
  208. They follow the same rules for encoding and decoding as the corresponding STL
  209. string type (for example, a ``std::u16string_view`` argument will be passed
  210. UTF-16-encoded data, and a returned ``std::string_view`` will be decoded as
  211. UTF-8).
  212. References
  213. ==========
  214. * `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/>`_
  215. * `C++ - Using STL Strings at Win32 API Boundaries <https://msdn.microsoft.com/en-ca/magazine/mt238407.aspx>`_