LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 171|回复: 0

给扩展函数的关键字参数

[复制链接]
发表于 2024-1-16 15:35:01 | 显示全部楼层 |阅读模式
给扩展函数的关键字参数
函数 PyArg_ParseTupleAndKeywords() 声明如下:

int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                const char *format, char *kwlist[], ...);
arg 与 format 形参与 PyArg_ParseTuple() 函数所定义的一致。 kwdict 形参是作为第三个参数从 Python 运行时接收的关键字字典。 kwlist 形参是以 NULL 结尾的字符串列表,它被用来标识形参;名称从左至右与来自 format 的类型信息相匹配。 如果执行成功,PyArg_ParseTupleAndKeywords() 会返回真值,否则返回假值并引发一个适当的异常。

备注 嵌套的元组在使用关键字参数时无法生效,不在 kwlist 中的关键字参数会导致 TypeError 异常。
如下例子是使用关键字参数的例子模块,作者是 Geoff Philbrick (philbrick@hks.com):

#define PY_SSIZE_T_CLEAN  /* Make "s#" use Py_ssize_t rather than int. */
#include <;Python.h>

static PyObject *
keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
{
    int voltage;
    const char *state = "a stiff";
    const char *action = "voom";
    const char *type = "Norwegian Blue";

    static char *kwlist[] = {"voltage", "state", "action", "type", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
                                     &voltage, &state, &action, &type))
        return NULL;

    printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
           action, voltage);
    printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);

    Py_RETURN_NONE;
}

static PyMethodDef keywdarg_methods[] = {
    /* The cast of the function is necessary since PyCFunction values
     * only take two PyObject* parameters, and keywdarg_parrot() takes
     * three.
     */
    {"parrot", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
     "Print a lovely skit to standard output."},
    {NULL, NULL, 0, NULL}   /* sentinel */
};

static struct PyModuleDef keywdargmodule = {
    PyModuleDef_HEAD_INIT,
    "keywdarg",
    NULL,
    -1,
    keywdarg_methods
};

PyMODINIT_FUNC
PyInit_keywdarg(void)
{
    return PyModule_Create(&keywdargmodule);
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表