aboutsummaryrefslogtreecommitdiffstats
path: root/sources/shiboken6/libshiboken/sbkcppstring.cpp
blob: 8e8324f5ef50d40c9c7aeda3475f5d93b479753f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "sbkcppstring.h"
#include "autodecref.h"

namespace Shiboken::String
{

PyObject *fromCppString(const std::string &value)
{
    return PyUnicode_FromStringAndSize(value.data(), value.size());
}

PyObject *fromCppStringView(std::string_view value)
{
    return PyUnicode_FromStringAndSize(value.data(), value.size());
}

PyObject *fromCppWString(const std::wstring &value)
{
    return PyUnicode_FromWideChar(value.data(), value.size());
}

void toCppString(PyObject *str, std::string *value)
{
    value->clear();

    if (str == Py_None)
        return;

    if (PyUnicode_Check(str)) {
        if (PyUnicode_GetLength(str) > 0)
            value->assign(_PepUnicode_AsString(str));
        return;
    }

    if (PyBytes_Check(str))
        value->assign(PyBytes_AS_STRING(str));
}

void toCppWString(PyObject *str, std::wstring *value)
{
    value->clear();

    if (str == Py_None || PyUnicode_Check(str) == 0 || PyUnicode_GetLength(str) == 0)
        return;

    wchar_t *w = PyUnicode_AsWideCharString(str, nullptr);
    value->assign(w);
    PyMem_Free(w);
}

} // namespace Shiboken::String