PyArg_ParseTuple() 函数声明如下:
int PyArg_ParseTuple(PyObject *arg, char *format, ...);
arg参数必须是元组对象,该元组包含从Python传递到C函数的参数列表。 format参数的格式必须是一个格式化的字符串, 格式化字符串的语法在"Parsing arguments and building values" 的Python/C API Reference Manual章节中解释,其他参数必须是变量地址,其类型有格式化字符串参数决定。
注意:当PyArg_ParseTuple()函数检查Python参数需要的类型时,不能检查调用传入C变量地址的有效性:如果你输入错误,你的代码也许崩溃,或者至少是改写了内存的随机地址。所以请小心!
注意任何提供给调用者的Python对象引用是borrowed引用,不增加引用计数。
一些调用例子:
int ok;
int i, j;
long k, l;
const char *s;
int size;
ok = PyArg_ParseTuple(args, ""); /* No arguments */
/* Python call: f() */
ok = PyArg_ParseTuple(args, "s", &s); /* A string */
/* Possible Python call: f('whoops!') */
ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
/* Possible Python call: f(1, 2, 'three') */
ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
/* A pair of ints and a string, whose size is also returned */
/* Possible Python call: f((1, 2), 'three') */
{
const char *file;
const char *mode = "r";
int bufsize = 0;
ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
/* A string, and optionally another string and an integer */
/* Possible Python calls:
f('spam')
f('spam', 'w')
f('spam', 'wb', 100000) */
}
{
int left, top, right, bottom, h, v;
ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
&left, &top, &right, &bottom, &h, &v);
/* A rectangle and a point */
/* Possible Python call:
f(((0, 0), (400, 300)), (10, 10)) */
}
{
Py_complex c;
ok = PyArg_ParseTuple(args, "D:myfunction", &c);
/* a complex, also providing a function name for errors */
/* Possible Python call: myfunction(1+2j) */
}