Skip to content

Instantly share code, notes, and snippets.

@rossbar
Created July 21, 2021 16:58
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 rossbar/b48b5a3c57384cb37133c55f23fc575d to your computer and use it in GitHub Desktop.
Save rossbar/b48b5a3c57384cb37133c55f23fc575d to your computer and use it in GitHub Desktop.
Python C-API Extension tutorial: https://docs.python.org/3/extending/extending.html
from setuptools import setup, find_packages, Extension
ext_modules=[Extension("spam", ["spam.c"])]
if __name__ == "__main__":
setup(
name="spam",
packages=find_packages(),
ext_modules=ext_modules,
)
#define PY_SSIZE_T_CLEAN
#include <Python.h>
static PyObject *
spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return PyLong_FromLong(sts);
}
static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS,
"Execute a shell command."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef spammodule = {
PyModuleDef_HEAD_INIT,
"spam", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
SpamMethods
};
PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModule_Create(&spammodule);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment