Created
July 21, 2021 16:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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