1.7 Extracting Parameters in Extension Functions
The PyArg_ParseTuple() function is declared as follows:
PyArg_ParseTuple()函数是以以下形式声明的
int PyArg_ParseTuple(PyObject *arg, char *format, …);
The argargument must be a tuple object containing an argument list passed from Python to a C function. The formatargument must be a format string, whose syntax is explained in “Parsing arguments and building values” in the Python/C API Reference Manual. The remaining arguments must be addresses of variables whose type is determined by the format string.
arg参数必须是一个由Python传入C函数的存储了参数列表的元组对象。format参数必须为一个格式字符串,格式字符的语法在Python/C API Reference Manual中的Parsing arguments and building values说明了。余下的参数必须为变量的地址,变量的类型由格式字符串决定。
Note that while PyArg_ParseTuple() checks that the Python arguments have the required types, it cannot check the validity of the addresses of C variables passed to the call: if you make mistakes there, your code will probably crash or at least overwrite random bits in memory. So be careful!
注意,虽然可以检测Python的参数类型是否符合要求,但却不能检测传入到调用者的C变量的地址的可用性:如果你在那里犯错了,你的代码可能发生冲突,至少也会导致随机覆盖重写内存中的位。因而要小心!
Note that any Python object references which are provided to the caller are borrowed references;do not decrement their reference count!
注意,任何提供给调用者的Python对象的引用都是借引用,所以不要减少它们的引用计数。
Some example calls:
一些调用的例子:
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) */
}
No comments:
Post a Comment