You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

303 lines
9.0 KiB

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