首页 > 解决方案 > Python C API Unicode 参数到 std::wstring

问题描述

https://docs.python.org/3/extending/extending.html#keyword-parameters-for-extension-functions之后,我声明了以下函数:

PyObject* myFunction(PyObject *self, PyObject *args, PyObject *keywds) {
    const wchar_t *query;
    std::size_t query_len;
    PyObject* py_choices;
    double score_cutoff = 0;
    bool preprocess = true;
    static const char *kwlist[] = {"query", "choices", "score_cutoff", "preprocess", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "u#O|dp", const_cast<char **>(kwlist),
                                     &query, &query_len, &py_choices, &score_cutoff, &preprocess)) {
        return NULL;
    }

    PyObject* choices = PySequence_Fast(py_choices, "Choices must be a sequence of strings");
    if (!choices) {
        return NULL;
    }

    std::size_t choice_count = PySequence_Fast_GET_SIZE(choices);
    std::wstring query_str(query, query_len);

    for (std::size_t i = 0; i < choice_count; ++i) {
        PyObject* py_choice = PySequence_Fast_GET_ITEM(choices, i);

        const wchar_t *choice;
        std::size_t choice_len;
        if (!PyArg_Parse(py_choice, "u#", &choice, &choice_len)) {
            PyErr_SetString(PyExc_TypeError, "Choices must be a sequence of strings");
            Py_DECREF(choices);
            return NULL;
        }

        std::wstring choice_str(choice, choice_len);

        // do some stuff with both strings
    }

    Py_DECREF(choices);
    Py_RETURN_NONE;
}

目标是在 python 中具有以下签名的函数

def myFunction(query: str, choices: Iterable[str], score_cutoff: float = 0, preprocess : bool = True):

在阅读了参数和命名参数后,我想将 unicode 字符串放在 std::wstring 中。

编辑:正如评论中所指出的,p格式需要使用整数,因为 c 确实具有 bool 数据类型

标签: pythonc++python-3.xpython-c-api

解决方案


推荐阅读