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