python - Calling numpy function from C-code -
i'm trying move matlab code mex extensions python numpy , scipy libraries. using wonderful tutorial http://www.scipy.org/cookbook/c_extensions/numpy_arrays, quite adopt c-functions calling python. c-functions call matlab functions, have substitute code calling numpy , scipy functions c-code.
i've tried extending , embedding python interpreter. however, faced problem: how pass array function argument. long way find function in module , build tuple arguments doesn't seems elegant.
so, how call sum function in numpy module c-code, example?
i'll appreciate ideas or links. ruben
p.s. here example:
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 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; } /* 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 new function argument */ pyobject *inarg = pytuple_new(1); if( inarg == null){ fprintf(stderr,"cannot convert build in value\n"); return null; } /* set 1 input paramter */ pytuple_setitem(inarg, 0, (pyobject*)vecin); /* call sunction module , 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); }
result of
>>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 argument not tuple segmentation fault
the numpy c api has pyarray_sum
:
pyobject *sum = pyarray_sum(arr, npy_maxdims, pyarray_descr(arr)->type_num, null);
Comments
Post a Comment