24.5. Python Unicode Strings and C++

This section looks at how you can bridge between Python and C++ unicode in Python extensions.

Whilst Python is Unicode aware C++ is not, well C++11 added std::basic_string specialisations for 2 and 4 byte ‘Unicode’ characters but these are just containers, they have no real awareness of what they contain.

24.5.1. Basic Handling of Unicode

The task here is to:

  1. Take any Python Unicode string as an argument.

  2. Convert it into an appropriate C++ container.

  3. Dump that C++ container out to std::cout.

  4. Create and new Python Unicode string from that C++ container and return it.

This is just show that we can round-trip between the internal representations of the two languages.

Here is the despatch function that takes a single Unicode argument (note the "U" specification) and calls the appropriate handling function:

 1/* Handler functions, defined later. */
 2PyObject *unicode_1_to_string_and_back(PyObject *py_str);
 3PyObject *unicode_2_to_string_and_back(PyObject *py_str);
 4PyObject *unicode_4_to_string_and_back(PyObject *py_str);
 5
 6static PyObject *
 7unicode_to_string_and_back(PyObject *Py_UNUSED(module), PyObject *args) {
 8    PyObject *py_str = NULL;
 9    PyObject *ret_val = NULL;
10    if (! PyArg_ParseTuple(args, "U", &py_str)) {
11        return NULL;
12    }
13    unicode_dump_as_1byte_string(py_str);
14    std::cout << "Native:" << std::endl;
15    switch (PyUnicode_KIND(py_str)) {
16        case PyUnicode_1BYTE_KIND:
17            ret_val = unicode_1_to_string_and_back(py_str);
18            break;
19        case PyUnicode_2BYTE_KIND:
20            ret_val = unicode_2_to_string_and_back(py_str);
21            break;
22        case PyUnicode_4BYTE_KIND:
23            ret_val = unicode_4_to_string_and_back(py_str);
24            break;
25        default:
26            PyErr_Format(PyExc_ValueError,
27                         "In %s argument is not recognised as a Unicode 1, 2, 4 byte string",
28                         __FUNCTION__);
29            ret_val = NULL;
30            break;
31    }
32    return ret_val;
33}

The three handler functions are here, they use std::string, std::u16string and std::u32string as appropriate:

 1static PyObject *
 2unicode_1_to_string_and_back(PyObject *py_str) {
 3    assert(PyUnicode_KIND(py_str) == PyUnicode_1BYTE_KIND);
 4    std::string result = std::string((char *) PyUnicode_1BYTE_DATA(py_str));
 5    dump_string(result);
 6    return PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND,
 7                                     result.c_str(),
 8                                     result.size());
 9}
10
11static PyObject *
12unicode_2_to_string_and_back(PyObject *py_str) {
13    assert(PyUnicode_KIND(py_str) == PyUnicode_2BYTE_KIND);
14    // NOTE: std::u16string is a std::basic_string<char16_t>
15    std::u16string result = std::u16string((char16_t *) PyUnicode_2BYTE_DATA(py_str));
16    dump_string(result);
17    return PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND,
18                                     result.c_str(),
19                                     result.size());
20}
21
22static PyObject *
23unicode_4_to_string_and_back(PyObject *py_str) {
24    assert(PyUnicode_KIND(py_str) == PyUnicode_4BYTE_KIND);
25    // NOTE: std::u32string is a std::basic_string<char32_t>
26    std::u32string result = std::u32string((char32_t *) PyUnicode_4BYTE_DATA(py_str));
27    dump_string(result);
28    return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
29                                     result.c_str(),
30                                     result.size());
31}

Each of these calls dump_string which is a template function that spits out the individual character values:

 1template <typename T>
 2void dump_string(const std::basic_string<T> &str) {
 3    std::cout << "String size: " << str.size();
 4    std::cout << " word size: " << sizeof(T) << std::endl;
 5    for (size_t i = 0; i < str.size(); ++i) {
 6        std::cout << std::setfill('0');
 7        std::cout << "0x" << std::hex;
 8        std::cout << std::setw(2 * sizeof(T)) << static_cast<int>(str[i]);
 9        std::cout << " " << std::dec << std::setw(8) << static_cast<int>(str[i]);
10        std::cout << std::setfill(' ');
11        std::cout << " \"" << str[i] << "\""<< std::endl;
12    }
13}

For completeness here is the module code that creates a cUnicode module with a single show() function:

 1static PyMethodDef cUnicode_Methods[] = {
 2    {"show", (PyCFunction)unicode_to_string_and_back, METH_VARARGS,
 3        "Convert a Python unicode string to std::string and back."},
 4    {NULL, NULL, 0, NULL}        /* Sentinel */
 5};
 6
 7static PyModuleDef cUnicodemodule = {
 8    PyModuleDef_HEAD_INIT,
 9    "cUnicode",
10    "cUnicode works with unicode strings.",
11    -1,
12    cUnicode_Methods,
13    NULL, NULL, NULL, NULL
14};
15
16PyMODINIT_FUNC
17PyInit_cUnicode(void)
18{
19    PyObject* m;
20
21    m = PyModule_Create(&cUnicodemodule);
22    if (m == NULL)
23        return NULL;
24    return m;
25}

The full code is in src/cpy/cpp/cUnicode.cpp and the tests are in tests/unit/test_c_cpp.py. Here is an example of using this module:

 1>>> from cPyExtPatt.cpp import cUnicode
 2>>> cUnicode.show('Hello')
 3String size: 5 word size: 1
 40x00000048       72 "H"
 50x00000065      101 "e"
 60x0000006c      108 "l"
 70x0000006c      108 "l"
 80x0000006f      111 "o"
 9'Hello'
10>>> s = "a\xac\u1234\u20ac\U00008000"
11>>> r = cUnicode.show(s)
12String size: 5 word size: 2
130x00000061       97 "97"
140x000000ac      172 "172"
150x00001234     4660 "4660"
160x000020ac     8364 "8364"
170x00008000    32768 "32768"
18>>> r == s
19True
20>>> s = "a\xac\u1234\u20ac\U00018000"
21>>> r = cUnicode.show(s)
22String size: 5 word size: 4
230x00000061       97 "97"
240x000000ac      172 "172"
250x00001234     4660 "4660"
260x000020ac     8364 "8364"
270x00018000    98304 "98304"
28>>> r == s
29True

24.5.2. Working with bytes, bytearray and UTF-8 Unicode Arguments

It is fairly common to want to convert an argumennt that is bytes, bytearray or UTF-8 to a std::string. This function will do just that:

 1/** Converting Python bytes and Unicode to and from std::string
 2 * Convert a PyObject to a std::string and return 0 if successful.
 3 * If py_str is Unicode than treat it as UTF-8.
 4 * This works with Python 2.7 and Python 3.4 onwards.
 5 */
 6static int
 7py_object_to_std_string(const PyObject *py_object, std::string &result, bool utf8_only = true) {
 8    result.clear();
 9    if (PyBytes_Check(py_object)) {
10        result = std::string(PyBytes_AS_STRING(py_object));
11        return 0;
12    }
13    if (PyByteArray_Check(py_object)) {
14        result = std::string(PyByteArray_AS_STRING(py_object));
15        return 0;
16    }
17    // Must be unicode then.
18    if (!PyUnicode_Check(py_object)) {
19        PyErr_Format(PyExc_ValueError,
20                     "In %s \"py_str\" failed PyUnicode_Check()",
21                     __FUNCTION__);
22        return -1;
23    }
24    if (PyUnicode_READY(py_object)) {
25        PyErr_Format(PyExc_ValueError,
26                     "In %s \"py_str\" failed PyUnicode_READY()",
27                     __FUNCTION__);
28        return -2;
29    }
30    if (utf8_only && PyUnicode_KIND(py_object) != PyUnicode_1BYTE_KIND) {
31        PyErr_Format(PyExc_ValueError,
32                     "In %s \"py_str\" not utf-8",
33                     __FUNCTION__);
34        return -3;
35    }
36    result = std::string((char *) PyUnicode_1BYTE_DATA(py_object));
37    return 0;
38}

And these three do the reverse:

 1static PyObject *
 2std_string_to_py_bytes(const std::string &str) {
 3    return PyBytes_FromStringAndSize(str.c_str(), str.size());
 4}
 5
 6static PyObject *
 7std_string_to_py_bytearray(const std::string &str) {
 8    return PyByteArray_FromStringAndSize(str.c_str(), str.size());
 9}
10
11static PyObject *
12std_string_to_py_utf8(const std::string &str) {
13    // Equivelent to:
14    // PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, str.c_str(), str.size());
15    return PyUnicode_FromStringAndSize(str.c_str(), str.size());
16}