Tutorial on Python C Extensions
The minimal module:
1#define PY_SSIZE_T_CLEAN
2#include <Python.h>
3
4static struct PyModuleDef demomodule = {
5 PyModuleDef_HEAD_INIT,
6 "demo",
7 NULL,
8 -1,
9 NULL
10};
11
12PyMODINIT_FUNC
13PyInit_demo(void)
14{
15 return PyModule_Create(&demomodule);
16}
The suffix of the PyInit_...
function in line 13 must match the
name of the C file name.
Let’s import it:
python3 -c 'import demo'
python3 -c 'import demo; print(help())'
We will now add module documentation:
1#define PY_SSIZE_T_CLEAN
2#include <Python.h>
3
4const char module_doc[] = "This is the demo module.";
5
6static struct PyModuleDef demomodule = {
7 PyModuleDef_HEAD_INIT,
8 "demo",
9 module_doc,
10 -1,
11 NULL
12};
13
14PyMODINIT_FUNC
15PyInit_demo(void)
16{
17 return PyModule_Create(&demomodule);
18}
Let’s add a function:
1#define PY_SSIZE_T_CLEAN
2#include <Python.h>
3
4const char module_doc[] = "This is the demo module.";
5
6static PyObject *
7demo_system(PyObject *self, PyObject *args)
8{
9 const char *command;
10 int sts;
11
12 if (!PyArg_ParseTuple(args, "s", &command))
13 return NULL;
14 sts = system(command);
15 if (sts < 0) {
16 return NULL;
17 }
18 return PyLong_FromLong(sts);
19}
20
21static PyMethodDef module_methods[] = {
22 {"system", demo_system, METH_VARARGS, "Execute a shell command."},
23 {NULL, NULL, 0, NULL}
24};
25
26
27static struct PyModuleDef demomodule = {
28 PyModuleDef_HEAD_INIT,
29 "demo",
30 module_doc,
31 -1,
32 module_methods
33};
34
35PyMODINIT_FUNC
36PyInit_demo(void)
37{
38 return PyModule_Create(&demomodule);
39}