|
| 1 | +#include <stdio.h> |
| 2 | +#include <Python.h> |
| 3 | + |
| 4 | +// Module method definitions |
| 5 | +static PyObject* my_sum_from_cpython(PyObject *self, PyObject *args) { |
| 6 | + PyObject *pList; |
| 7 | + PyObject *pItem; |
| 8 | + Py_ssize_t n; |
| 9 | + int i; |
| 10 | + if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &pList)) { |
| 11 | + PyErr_SetString(PyExc_TypeError, "parameter must be a list"); |
| 12 | + return NULL; |
| 13 | + } |
| 14 | + n = PyList_Size(pList); |
| 15 | + long sum = 0; |
| 16 | + for (i = 0; i < n; i++) { |
| 17 | + pItem = PyList_GetItem(pList, i); |
| 18 | + if (!PyLong_Check(pItem)) { |
| 19 | + return NULL; |
| 20 | + } |
| 21 | + sum += PyLong_AsLong(pItem); |
| 22 | + } |
| 23 | + return Py_BuildValue("l", sum); |
| 24 | +} |
| 25 | +// Method definition object for this extension, these argumens mean: |
| 26 | +// ml_name: The name of the method |
| 27 | +// ml_meth: Function pointer to the method implementation |
| 28 | +// ml_flags: Flags indicating special features of this method, such as |
| 29 | +// accepting arguments, accepting keyword arguments, being a |
| 30 | +// class method, or being a static method of a class. |
| 31 | +// ml_doc: Contents of this method's docstring |
| 32 | +static PyMethodDef sum_from_cpython_methods[] = { |
| 33 | + { |
| 34 | + "my_sum", my_sum_from_cpython, METH_VARARGS, "" |
| 35 | + }, |
| 36 | + {NULL, NULL, 0, NULL} |
| 37 | +}; |
| 38 | + |
| 39 | +// Module definition |
| 40 | +// The arguments of this structure tell Python what to call your extension, |
| 41 | +// what it's methods are and where to look for it's method definitions |
| 42 | +static struct PyModuleDef sum_from_cpython_definition = { |
| 43 | + PyModuleDef_HEAD_INIT, |
| 44 | + "sum_from_cpython", |
| 45 | + "A Python module that prints 'sum_from_cpython world' from C code.", |
| 46 | + -1, |
| 47 | + sum_from_cpython_methods |
| 48 | +}; |
| 49 | + |
| 50 | +// Module initialization |
| 51 | +// Python calls this function when importing your extension. It is important |
| 52 | +// that this function is named PyInit_[[your_module_name]] exactly, and matches |
| 53 | +// the name keyword argument in setup.py's setup() call. |
| 54 | +PyMODINIT_FUNC PyInit_sum_from_cpython(void) { |
| 55 | + Py_Initialize(); |
| 56 | + return PyModule_Create(&sum_from_cpython_definition); |
| 57 | +} |
0 commit comments