从ccd调用numpy函数

2024-10-01 11:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一些带有Mex扩展的MatLab代码移植到带有numpy和scipy库的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函数呢?在

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

注:这里有一个例子:

    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);
}

结果

^{pr2}$

Tags: 函数代码pynumpyreturnifstderrnull