我到处都找过,但找不到例子PyArg_ParseTupleAndKeywords()
与元组一起使用 — 包含可选参数 —and关键词。我发现的最接近的是这个问题 https://stackoverflow.com/questions/10625865/how-does-pyarg-parsetupleandkeywords-work/10625987#10625987,但答案并不是特别有帮助。大多数示例似乎都将关键字作为可选参数,但元组似乎也应该能够包含可选参数。
假设我正在尝试解析以下参数:
- numpy 双精度数组(强制)
- numpy 双精度数组(可选,无关键字)
- optional keyword arguments:
- k1 => numpy 双精度数组
- k2 => 整数
- k3 => 双
- k4 => Python 类实例
看来我应该做类似的事情
static PyObject* pymod_func(PyObject* self, PyObject* args, PyObject* kwargs) {
static char* keywords[] = {"k1", "k2", "k3", "k4", NULL};
PyObject *arg1, *arg2, *k1, *k4
PyObject *arr1, *arr2, *karr1;
double *k3;
int *k2;
PyArg_ParseTupleAndKeywords(args, kwargs, "O!|O!OidO", keywords, &arg1, &PyArray_Type, &arg2, &PyArray_Type, &k1, &PyArray_Type, &k2, &k3, &k4);
arr1 = PyArray_FROM_OTF(arg1, NPY_FLOAT64, NPY_ARRAY_INOUT_ARRAY);
if (arr1 == NULL) return NULL;
arr2 = PyArray_FROM_OTF(arg1, NPY_FLOAT64, NPY_ARRAY_INOUT_ARRAY);
// no null check, because optional
karr1 = PyArray_FROM_OTF(k1, NPY_FLOAT64, NPY_ARRAY_INOUT_ARRAY);
// again, no null check, because this is optional
// do things with k3, k2, and k4 also
return NULL;
}
我看过的其他地方,但没有找到太多帮助:
- https://docs.python.org/2/extending/extending.html https://docs.python.org/2/extending/extending.html
- https://docs.python.org/2/c-api/arg.html https://docs.python.org/2/c-api/arg.html
- http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.how-to-extend.html http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.how-to-extend.html
正确的使用方法是什么PyArg_ParseTupleAndKeywords()
?