- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我一直在尝试学习如何为 Python 编写 C 扩展,并希望确保我了解 PyArg_ParseTupleAndKeywords 的工作原理。
我相信第一个参数是一个 PyObject 指针,它指向一个参数数组,这些参数按照传递的顺序传递给 C 扩展函数。第二个参数是传递的关键字列表,它们传递的位置,很可能是某种指示标志,告诉关键字从哪个位置开始,位置变得无关紧要。
PyArg_ParseTupleAndKeywords 然后使用它的关键字列表(第 4 个参数)在用关键字指定的参数和格式字符串(第 3 个参数)和 C 变量的地址(第 5 个 & + 参数)之间进行映射,适当的值应该被复制到.
我的理解对吗?当我阅读在线文档时,我所看到的只是对“位置参数和关键字参数”的引用,这让我感觉有点一头雾水。处理 PyArg_ParseTupleAndKeywords 的 Python 解释器的文件在哪里?
最佳答案
在 python 中模拟以下内容:
def keywords(a, b, foo=None, bar=None, baz=None):
pass
以下将起作用:
static PyObject *keywords(PyObject *self, PyObject *args, PyObject *kwargs)
{
char *a;
char *b;
char *foo = NULL;
char *bar = NULL;
char *baz = NULL;
// Note how "a" and "b" are included in this
// even though they aren't supposed to be in kwargs like in python
static char *kwlist[] = {"a", "b", "foo", "bar", "baz", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ss|sss", kwlist,
&a, &b, &foo, &bar, &baz))
{
return NULL;
}
printf("a is %s\n", a);
printf("b is %s\n", b);
printf("foo is %s\n", foo);
printf("bar is %s\n", bar);
printf("baz is %s\n", baz);
Py_RETURN_NONE;
}
// ...
static PyMethodDef SpamMethods[] =
{
// ...
{"keywords", (PyCFunction) keywords, METH_VARARGS | METH_KEYWORDS, "practice kwargs"},
{NULL, NULL, 0, NULL}
// ...
}
并使用它:
from spam import keywords
keywords() # Fails, require a and b
keywords('a') # fails, requires b
keywords('a', 'b')
keywords('a', 'b', foo='foo', bar='bar', baz='baz')
keywords('a', 'b','foo', 'bar', 'baz')
keywords(a='a', b='b', foo='foo', bar='bar', baz='baz')
关于python - PyArg_ParseTupleAndKeywords 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10625865/
我在 C Python 扩展中对 PyArg_ParseTupleAndKeywords 进行了以下调用: static char *kwlist [] = { "page_slug", "k
我一直在尝试学习如何为 Python 编写 C 扩展,并希望确保我了解 PyArg_ParseTupleAndKeywords 的工作原理。 我相信第一个参数是一个 PyObject 指针,它指向一个
我到处都看过,但我找不到 PyArg_ParseTupleAndKeywords() 与元组一起使用的示例 - 包含可选参数 - 和 关键字。我找到的最接近的是 this question ,但答案并
我正在调用一个函数,它接受一个位置参数列表,后跟关键字参数。我想分别处理 args 和 kwargs。不幸的是,与位置参数的 PyArg_ParseTuple 不同,关键字参数没有等效的 PyArg_
我正在将扩展类型对象传递给 Python 函数,它需要将此类型的变量传递给 C 函数。我的扩展类型如下所示: typedef struct { PyObject_HEAD rec_rs
我目前正在使用 python4delphi 编写一个 Python 模块.我想使用标准 C API 函数 PyArg_ParseTupleAndKeywords . 从文档中可以看出签名是这样的: i
搜索有关如何使用 PyArg_ParseTupleAndKeywords 的示例我发现了这些问题: How can one use PyArg_ParseTupleAndKeywords to par
我是一名优秀的程序员,十分优秀!