Pythonからcallされるソースコード『py_list_param.c』
#include "../../../include/python3.6m/Python.h"
static PyObject* c_list_param(PyObject* self, PyObject* args)
{
int n;
long a, sum = 0;
PyObject* c_list, *item;
if (!PyArg_ParseTuple(args, "O", &c_list)){
return NULL;
}
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 = PyLong_AsLong(item);
sum = sum + a;
Py_DECREF(item);
}
Py_DECREF(c_list);
return Py_BuildValue("l", sum);
}
static PyMethodDef listpMethods[] = {
{ "sum_list", c_list_param, METH_VARARGS, "Calculate list sum"},
{ NULL }
};
static struct PyModuleDef listpModule = {
PyModuleDef_HEAD_INIT,
"listpModule",
"Python3 C API Module(Sample 4)",
-1,
listpMethods
};
PyMODINIT_FUNC PyInit_listpModule(void)
{
return PyModule_Create(&listpModule);
}
setup.py
from distutils.core import setup, Extension
setup(name = 'listpModule', version = '1.0.0', \
ext_modules = [Extension('listpModule', ['py_list_param.c'])])
『py_list_param.c』を呼ぶソースコード『list_param.py』
import listpModule as lpm
py_list = [1, 2, 3]
sum = lpm.sum_list(py_list)
print(sum)