Created
March 29, 2018 12:57
-
-
Save myersguo/ea12aa987c888431ad097bb18ff06b64 to your computer and use it in GitHub Desktop.
python c module example
This file contains hidden or 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
#include <Python.h> | |
static PyObject *SpamError; | |
static PyObject * | |
spam_system(PyObject *self, PyObject *args) | |
{ | |
const char *command; | |
int sts; | |
if (!PyArg_ParseTuple(args, "s", &command)) | |
return NULL; | |
sts = system(command); | |
if (sts < 0) { | |
PyErr_SetString(SpamError, "System command failed"); | |
return NULL; | |
} | |
return PyLong_FromLong(sts); | |
} | |
static PyMethodDef SpamMethods[] = { | |
{"system", spam_system, METH_VARARGS, | |
"Execute a shell command."}, | |
{NULL, NULL, 0, NULL} /* Sentinel */ | |
}; | |
PyMODINIT_FUNC | |
initspam(void) | |
{ | |
PyObject *m; | |
m = Py_InitModule("spam", SpamMethods); | |
if (m == NULL) | |
return; | |
SpamError = PyErr_NewException("spam.error", NULL, NULL); | |
Py_INCREF(SpamError); | |
PyModule_AddObject(m, "error", SpamError); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
gcc spammify.c -fPIC -I/usr/include/python2.7 -shared -o spam.so