Pass an array of floats from Python and return the sum and average in tuples.
capi.py
import myModule as capi
import random
x=[random.uniform(0, 100) for x in range(100)]
s=0.0
for a in x:
s=s+a
print("c ",s,s/len(x))
a=capi.fsum_avr(x)
print("py",a)
When you run
>python capi.py
py 5025.24247203747 50.252424720374705
c (5025.24247203747, 50.252424720374705)
capilib.c
#include <Python.h>
static PyObject* fsum_avr(PyObject* self, PyObject* args)
{
long n;
double sum=0.0,avr,a;
PyObject* c_list, *item;
if (!PyArg_ParseTuple(args, "O", &c_list)) return NULL;
// Check list
if PyList_Check(c_list) n = PyList_Size(c_list);
else return NULL;
for (int i = 0; i < n; i++){
item = PyList_GetItem(c_list, i);
a = PyFloat_AsDouble(item); // Increment the reference count
sum = sum + a;
Py_DECREF(item); // Decrement the reference count
}
avr=sum/n;
return Py_BuildValue("(dd)",sum,avr);
}
static PyMethodDef myMethods[] = {
{ "fsum_avr",fsum_avr, METH_VARARGS, "sum avr"},
{ NULL }
};
static struct PyModuleDef myModule = {
PyModuleDef_HEAD_INIT,"myModule","C API Module",-1,myMethods
};
PyMODINIT_FUNC PyInit_myModule(void){
return PyModule_Create(&myModule);
}
** Attention point **
Please see the link for ** Argument Interpretation and Value **.
setup.py
from distutils.core import setup, Extension
setup(name = 'myModule', version = '1.0.0', \
ext_modules = [Extension('myModule', ['capilib.c'])])
** Creating a library **
capi>python setup.py install
Recommended Posts