0

following https://docs.python.org/3/extending/extending.html#keyword-parameters-for-extension-functions I declared the following function:

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;
}

the goal was a function with the following signature in python

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

After reading the arguments and named arguments I would like to place the unicode strings in a std::wstring.

Edit: As pointed out in the comments the p format requires the use of an integer since c does have a bool data type

maxbachmann
  • 2,862
  • 1
  • 11
  • 35
  • 1
    `p` converts a _Python_ bool to a C int. It doesn't accept a c++ bool (because it's a C interface and bool isn't a data-type there) – DavidW Apr 03 '20 at 06:29
  • Oh well apparently I did not work with C for a to long time. Thanks for pointing out ;) – maxbachmann Apr 03 '20 at 08:05

0 Answers0