Pythonからcallされるソースコード『py_list_list.c』
#include "../../../include/python3.6m/Python.h"
static PyObject* c_multiply_list(PyObject* c_list, int n)
{
long a;
PyObject* result_list, *item;
result_list = PyList_New(n);
for (int i = 0; i < n; i++){
item = PyList_GetItem(c_list, i);
a = PyLong_AsLong(item);
a = 2 * a;
item = Py_BuildValue("l", a);
PyList_SET_ITEM(result_list, i, item);
Py_DECREF(item);
}
Py_DECREF(c_list);
return result_list;
}
static PyObject* py_list(PyObject* self, PyObject* args)
{
int n;
PyObject* c_list;
if (!PyArg_ParseTuple(args, "O", &c_list)){
return NULL;
}
if PyList_Check(c_list){
n = PyList_Size(c_list);
}else{
return NULL;
}
return c_multiply_list(c_list, n);
}
static PyMethodDef MultiplyList[] = {
{ "c_multiply_list", py_list, METH_VARARGS, "Multiply 2 and item of list "},
{ NULL }
};
static struct PyModuleDef multiplyList = {
PyModuleDef_HEAD_INIT,
"multiplyList",
"Python3 C API Module(Sample 5)",
-1,
MultiplyList
};
PyMODINIT_FUNC PyInit_multiplyList(void)
{
return PyModule_Create(&multiplyList);
}
setup.py
from distutils.core import setup, Extension
setup(name = 'multiplyList', version = '1.0.0', \
ext_modules = [Extension('multiplyList', ['py_list_list.c'])])
『py_list_list.c』を呼ぶソースコード『multiply_list.py』
import multiplyList as mlist
py_list = [1, 2, 3]
result_list = mlist.c_multiply_list(py_list)
print(result_list)