【发布时间】:2016-01-28 17:31:08
【问题描述】:
我到处寻找,但找不到PyArg_ParseTupleAndKeywords() 与元组一起使用的示例——包含可选参数——和关键字。我找到的最接近的是this question,但答案并不是特别有用。大多数示例似乎将关键字作为可选参数,但元组似乎也应该能够包含可选参数。
假设我正在尝试解析以下参数:
- numpy 双精度数组(强制)
- numpy 双精度数组(可选,无关键字)
- 可选关键字参数:
- 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/c-api/arg.html
- http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.how-to-extend.html
PyArg_ParseTupleAndKeywords()的正确使用方式是什么?
【问题讨论】:
标签: python python-2.7 numpy