python-c

A small Python module in C
git clone https://git.tronto.net/python-c
Download | Log | Files | Refs | README

commit 5f9adbf56b8dd9d2bc3c83b52eeb4073f7464455
Author: Sebastiano Tronto <sebastiano@tronto.net>
Date:   Mon,  7 Oct 2024 11:00:04 +0200

Initial commit

Diffstat:
A.gitignore | 2++
AMakefile | 12++++++++++++
AREADME.md | 16++++++++++++++++
Asum.c | 1+
Asum.h | 1+
Asum_module.c | 31+++++++++++++++++++++++++++++++
6 files changed, 63 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,2 @@ +*.o +*.so diff --git a/Makefile 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 @@ -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 @@ -0,0 +1 @@ +int sum(int a, int b) { return a+b; } diff --git a/sum.h b/sum.h @@ -0,0 +1 @@ +int sum(int, int); diff --git a/sum_module.c b/sum_module.c @@ -0,0 +1,31 @@ +#include "sum.h" + +#define PY_SSIZE_T_CLEAN +#include <Python.h> + +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); +}