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) */
}