【发布时间】:2011-12-21 13:30:15
【问题描述】:
我试图弄清楚如何在 C 扩展模块中为函数提供一个变量(并且可能)大量参数。
阅读PyArg_ParseTuple 似乎您必须知道要接受多少,有些是强制性的,有些是可选的,但都有自己的变量。我希望PyArg_UnpackTuple 能够处理这个问题,但是当我尝试以错误的方式使用它时,它似乎只会给我总线错误。
以以下 Python 代码为例,您可能希望将其制作成扩展模块(C 语言)。
def hypot(*vals):
if len(vals) !=1 :
return math.sqrt(sum((v ** 2 for v in vals)))
else:
return math.sqrt(sum((v ** 2 for v in vals[0])))
这可以使用任意数量的参数调用或迭代,hypot(3,4,5)、hypot([3,4,5]) 和 hypot(*[3,4,5]) 都给出相同的答案。
我的 C 函数的开头是这样的
static PyObject *hypot_tb(PyObject *self, PyObject *args) {
// lots of code
// PyArg_ParseTuple or PyArg_UnpackTuple
}
许多人认为yasar11732。接下来的人是一个完全工作的扩展模块(_toolboxmodule.c),它简单地接受任何数字或整数参数并返回由这些参数组成的列表(名称很差)。一个玩具,但说明了需要做什么。
#include <Python.h>
int ParseArguments(long arr[],Py_ssize_t size, PyObject *args) {
/* Get arbitrary number of positive numbers from Py_Tuple */
Py_ssize_t i;
PyObject *temp_p, *temp_p2;
for (i=0;i<size;i++) {
temp_p = PyTuple_GetItem(args,i);
if(temp_p == NULL) {return NULL;}
/* Check if temp_p is numeric */
if (PyNumber_Check(temp_p) != 1) {
PyErr_SetString(PyExc_TypeError,"Non-numeric argument.");
return NULL;
}
/* Convert number to python long and than C unsigned long */
temp_p2 = PyNumber_Long(temp_p);
arr[i] = PyLong_AsUnsignedLong(temp_p2);
Py_DECREF(temp_p2);
}
return 1;
}
static PyObject *hypot_tb(PyObject *self, PyObject *args)
{
Py_ssize_t TupleSize = PyTuple_Size(args);
long *nums = malloc(TupleSize * sizeof(unsigned long));
PyObject *list_out;
int i;
if(!TupleSize) {
if(!PyErr_Occurred())
PyErr_SetString(PyExc_TypeError,"You must supply at least one argument.");
return NULL;
}
if (!(ParseArguments(nums, TupleSize, args)) {
free(nums);
return NULL;
}
list_out = PyList_New(TupleSize);
for(i=0;i<TupleSize;i++)
PyList_SET_ITEM(list_out, i, PyInt_FromLong(nums[i]));
free(nums);
return (PyObject *)list_out;
}
static PyMethodDef toolbox_methods[] = {
{ "hypot", (PyCFunction)hypot_tb, METH_VARARGS,
"Add docs here\n"},
// NULL terminate Python looking at the object
{ NULL, NULL, 0, NULL }
};
PyMODINIT_FUNC init_toolbox(void) {
Py_InitModule3("_toolbox", toolbox_methods,
"toolbox module");
}
在python中是:
>>> import _toolbox
>>> _toolbox.hypot(*range(4, 10))
[4, 5, 6, 7, 8, 9]
【问题讨论】:
-
您为什么告诉我们您在使用
PyArg_*函数时遇到崩溃/遇到困难,然后向我们展示除了您如何使用PyArg_*函数之外的所有内容? -
您应该将 ParseArguments 放在 if 语句中,以查看解析过程中是否有错误(返回 null),如果有错误,请进行清理并返回 null。否则,您将在参数解析期间抑制错误。
-
是的,是的,你是对的。我会编辑帖子。
标签: python c python-c-extension