From 5f9adbf56b8dd9d2bc3c83b52eeb4073f7464455 Mon Sep 17 00:00:00 2001 From: Sebastiano Tronto Date: Mon, 7 Oct 2024 11:00:04 +0200 Subject: Initial commit --- .gitignore | 2 ++ Makefile | 12 ++++++++++++ README.md | 16 ++++++++++++++++ sum.c | 1 + sum.h | 1 + sum_module.c | 31 +++++++++++++++++++++++++++++++ 6 files changed, 63 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 README.md create mode 100644 sum.c create mode 100644 sum.h create mode 100644 sum_module.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9d22eb4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.o +*.so diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..44c43bf --- /dev/null +++ b/Makefile @@ -0,0 +1,12 @@ +all: sum.o sum_module.so + +sum.o: + cc -c -o sum.o sum.c + +sum_module.so: + cc -shared -I/usr/include/python3.12 -o sum_module.so sum.o sum_module.c + +clean: + rm -rf *.o *.so + +.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 @@ +# A tiny demo for a Python module in C + +This repo contains a Python module written in C with only one function. + +Works on my machineā„¢. To make it works on yours: + +1. Install the python development package. It is usually called `python3-dev` + or `python3-devel`. +2. Compile this module with `make`. +3. Open `python` and enjoy! + +``` +>>> import sum_module +>>> sum_module.sum_from_c(23, 19) +42 +``` 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 @@ +#include "sum.h" + +#define PY_SSIZE_T_CLEAN +#include + +static PyObject *csum(PyObject *self, PyObject *args) { + int a, b, result; + + if (!PyArg_ParseTuple(args, "ii", &a, &b)) + return NULL; + + result = sum(a, b); + return PyLong_FromLong(result); +} + +static PyMethodDef SumMethods[] = { + { "sum_from_c", csum, METH_VARARGS, "Sum two integers." }, + { NULL, NULL, 0, NULL } +}; + +static struct PyModuleDef summodule = { + PyModuleDef_HEAD_INIT, + "sum", + NULL, + -1, + SumMethods +}; + +PyMODINIT_FUNC PyInit_sum_module(void) { + return PyModule_Create(&summodule); +} -- cgit v1.3