Python扩展模块支持可变数量的参数

14
我正在尝试弄清楚如何在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_*函数以外的所有内容呢? - Karl Knechtel
你应该把ParseArguments放在一个if语句中,以检查在解析时是否存在错误(返回null),如果有错误则进行清理并返回null。否则,你将会压制参数解析期间的错误。 - yasar
是的,你说得对。我会编辑帖子。 - Brian Larsen
1个回答

11

我之前也用过这样的东西。可能是由于我不是有经验的C编码人员,所以它可能是错误的代码,但是它对我起作用了。这个想法是,*args只是一个Python元组,您可以做任何您可以使用Python元组做的事情。您可以查看http://docs.python.org/c-api/tuple.html

int
ParseArguments(unsigned 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);
        if (arr[i] == 0) {
            PyErr_SetString(PyExc_ValueError,"Zero doesn't allowed as argument.");
            return NULL;
        }
        if (PyErr_Occurred()) {return NULL; }
    }

    return 1;
}

我是这样调用这个函数的:

static PyObject *
function_name_was_here(PyObject *self, PyObject *args)
{
    Py_ssize_t TupleSize = PyTuple_Size(args);
    Py_ssize_t i;
    struct bigcouples *temp = malloc(sizeof(struct bigcouples));
    unsigned long current;

    if(!TupleSize) {
        if(!PyErr_Occurred()) 
            PyErr_SetString(PyExc_TypeError,"You must supply at least one argument.");
        free(temp);
        return NULL;
    }

    unsigned long *nums = malloc(TupleSize * sizeof(unsigned long));

    if(!ParseArguments(nums, TupleSize, args)){
        /* Make a cleanup and than return null*/
        return null;
    }

1
哇,我很高兴我问了你;你解决了我的问题。稍微调整一下,我的问题就解决了。我会根据你的解决方案编辑我的问题,并提供完全可行的解决方案给下一个人。 - Brian Larsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接