Extension Example 1. Python Call C function (Python 3.4)
1.1 spam.c
#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 */
};
static struct PyModuleDef spammodule = {
PyModuleDef_HEAD_INIT,
"spam", /* name of module */
NULL, // spam_doc, /* 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)
{
PyObject *m;
m = PyModule_Create(&spammodule);
if(m == NULL) return NULL;
SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_INCREF(SpamError);
PyModule_AddObject(m, "error", SpamError);
return m;
}
1.2 sp.py
#!/usr/local/bin/python3
import spam
status = spam.system("ls -l")
1.3 setup.py
from distutils.core import setup, Extension
setup(name='spam', version='1.0', ext_modules=[Extension('spam', ['spam.c'])])
1.4 build and install spam module
python3 setup.py install
1.5 execute sp.py
./sp.py