从C代码调用numpy函数

时间:2013-04-18 03:30:34

标签: python numpy python-c-api python-c-extension

我正在尝试使用numpy和scipy库将一些带有Mex扩展的MatLab代码移动到Python中。使用这个精彩的教程http://www.scipy.org/Cookbook/C_Extensions/NumPy_arrays,我很快就采用C函数从Python调用。但是有些C函数调用MatLab函数,所以我必须通过从C代码调用numpy和scipy函数来替换这段代码。

我试图做这样的事情Extending and Embedding the Python Interpreter。但是,我遇到了问题:如何将数组传递给函数参数。此外,在模块中查找函数然后为参数构建元组的这种漫长的方式似乎并不优雅。

那么,如何从C代码调用numpy模块中的sum函数,例如?

我会感激任何想法或链接。 鲁

P.S。这是一个例子:

    PyObject *feedback(PyObject *self, PyObject *args){
    PyArrayObject *Vecin;
    double mp=0,ret;
    if( !PyArg_ParseTuple(args,"O!d",&PyArray_Type,&Vecin,&mp)
      ||  Vecin == NULL ) return NULL;
    /* make python string with module name */
    PyObject *pName = PyString_FromString("numpy");
    if( pName == NULL){
        fprintf(stderr,"Couldn\'t setup string %s\n","numpy");
        return NULL;
    }
    /* import module */
    PyObject *pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    if( pModule == NULL){
        fprintf(stderr,"Couldn\'t find module %s\n","numpy");
        return NULL;
    }
    /* get module dict */
    PyObject *dic = PyModule_GetDict(pModule);
    if( dic == NULL){
        fprintf(stderr,"Couldn\'t find dic in module %s\n","numpy");
        return NULL;
    }
    /* find function */
    PyObject *pFunction = PyDict_GetItemString(dic, "sum");
    Py_DECREF(dic);
    if( pFunction == NULL){
        fprintf(stderr,"Couldn\'t find function  %s in dic\n","sum");
        return NULL;
    }
    Py_DECREF(pModule);
    /* create typle for new function argument */
    PyObject *inarg = PyTuple_New(1);
    if( inarg == NULL){
        fprintf(stderr,"Cannot convert to Build in Value\n");
        return NULL;
    }
    /* set one input paramter */
    PyTuple_SetItem(inarg, 0, (PyObject*)Vecin);
    /* call sunction from module and get result*/
    PyObject *value = PyObject_CallObject(pFunction, inarg);
    if( value == NULL){
        fprintf(stderr,"Function return NULL pointer\n");
        return NULL;
    }
    Py_DECREF(pFunction);
    if( !PyArg_ParseTuple(value,"d",&ret) ) return NULL;
    return Py_BuildValue("d",ret*mp);
}

的结果
>>print mymod.FeedBack(np.array([1.,2.,3.,4.,5.]),2)


Traceback (most recent call last):
  File "mymodtest.py", line 10, in <module>
    print mymod.FeedBack(np.array([1.,2.,3.,4.,5.]),2)
SystemError: new style getargs format but argument is not a tuple
Segmentation fault

1 个答案:

答案 0 :(得分:1)

NumPy C API有PyArray_Sum

PyObject *sum = PyArray_Sum(arr, NPY_MAXDIMS, PyArray_DESCR(arr)->type_num, NULL);
相关问题