Skip to content

Instantly share code, notes, and snippets.

@derrickturk
Last active September 22, 2020 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derrickturk/7d4cd9d3f42215d546ede3d8870f3c3c to your computer and use it in GitHub Desktop.
Save derrickturk/7d4cd9d3f42215d546ede3d8870f3c3c to your computer and use it in GitHub Desktop.
A minimal Python module in C, with MinGW makefile
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stddef.h>
PyObject *cpytest_add(PyObject *module, PyObject *args)
{
PyObject *lhs, *rhs;
if (!PyArg_ParseTuple(args, "OO", &lhs, &rhs))
return NULL;
return PyNumber_Add(lhs, rhs);
}
PyObject *cpytest_addi(PyObject *module, PyObject *args)
{
long lhs, rhs;
if (!PyArg_ParseTuple(args, "ll", &lhs, &rhs))
return NULL;
return PyLong_FromLong(lhs + rhs);
}
PyMethodDef cpytest_methods[] = {
{ "add", cpytest_add, METH_VARARGS, "add two things" },
{ "addi", cpytest_addi, METH_VARARGS, "add two integers" },
{ NULL, NULL, 0, NULL },
};
struct PyModuleDef cpytest = {
PyModuleDef_HEAD_INIT,
"cpytest",
NULL,
-1,
cpytest_methods
};
PyMODINIT_FUNC
PyInit_cpytest(void)
{
return PyModule_Create(&cpytest);
}
CC=gcc
COPTS=-Wall -pedantic -std=c99 -O2 -static
PYROOT=C:/Users/Derrick/local
PYVER=36
PYINCLUDEDIR=$(PYROOT)/Python$(PYVER)/include
PYLIBDIR=$(PYROOT)/Python$(PYVER)/libs
cpytest.pyd: cpytest.c
$(CC) $(COPTS) -shared -I$(PYINCLUDEDIR) -L$(PYLIBDIR) -o $@ $^ -lpython$(PYVER)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment