aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore2
-rw-r--r--Makefile12
-rw-r--r--README.md16
-rw-r--r--sum.c1
-rw-r--r--sum.h1
-rw-r--r--sum_module.c31
6 files changed, 63 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..9d22eb4
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
1*.o
2*.so
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..44c43bf
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,12 @@
1all: sum.o sum_module.so
2
3sum.o:
4 cc -c -o sum.o sum.c
5
6sum_module.so:
7 cc -shared -I/usr/include/python3.12 -o sum_module.so sum.o sum_module.c
8
9clean:
10 rm -rf *.o *.so
11
12.PHONY: all clean
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..071d2e7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,16 @@
1# A tiny demo for a Python module in C
2
3This repo contains a Python module written in C with only one function.
4
5Works on my machineā„¢. To make it works on yours:
6
71. Install the python development package. It is usually called `python3-dev`
8 or `python3-devel`.
92. Compile this module with `make`.
103. Open `python` and enjoy!
11
12```
13>>> import sum_module
14>>> sum_module.sum_from_c(23, 19)
1542
16```
diff --git a/sum.c b/sum.c
new file mode 100644
index 0000000..d3603fc
--- /dev/null
+++ b/sum.c
@@ -0,0 +1 @@
int sum(int a, int b) { return a+b; }
diff --git a/sum.h b/sum.h
new file mode 100644
index 0000000..3813423
--- /dev/null
+++ b/sum.h
@@ -0,0 +1 @@
int sum(int, int);
diff --git a/sum_module.c b/sum_module.c
new file mode 100644
index 0000000..5f55747
--- /dev/null
+++ b/sum_module.c
@@ -0,0 +1,31 @@
1#include "sum.h"
2
3#define PY_SSIZE_T_CLEAN
4#include <Python.h>
5
6static PyObject *csum(PyObject *self, PyObject *args) {
7 int a, b, result;
8
9 if (!PyArg_ParseTuple(args, "ii", &a, &b))
10 return NULL;
11
12 result = sum(a, b);
13 return PyLong_FromLong(result);
14}
15
16static PyMethodDef SumMethods[] = {
17 { "sum_from_c", csum, METH_VARARGS, "Sum two integers." },
18 { NULL, NULL, 0, NULL }
19};
20
21static struct PyModuleDef summodule = {
22 PyModuleDef_HEAD_INIT,
23 "sum",
24 NULL,
25 -1,
26 SumMethods
27};
28
29PyMODINIT_FUNC PyInit_sum_module(void) {
30 return PyModule_Create(&summodule);
31}

Generated with cgit - Back to sebastiano.tronto.net