In order to allow Python to call these functions, we need to “wrap” them with code that can interface with Python's C API
/* file: spamwrapper.c */
/* Defines a "spam" Python extension module */
/* Include the Python C API */
#include "Python.h"
/* External declarations to functions in spam.c */
extern int gcd(int,int);
extern void print_data(char *, char *, char *);
/* Wrapper for the gcd() function */
PyObject *spam_gcd(PyObject *self, PyObject *args) {
int x, y, g;
/* Get Python arguments */
if (!PyArg_ParseTuple(args, "ii", &x, &y)) {
return NULL;
}
/* Call the C function */
g = gcd(x,y);
return Py_BuildValue("i", g);
}
/* Wrapper for the print_data() function */
PyObject *spam_print_data(PyObject *self, PyObject *args, PyObject *kwargs) {
char *name = "None";
char *email = "None";
char *phone = "None";
static char *argnames[] = {"name","email","phone",NULL};
/* Get Python arguments */
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|sss", argnames, &name, &email, &phone)) {
return NULL;
}
/* Call the C function */
print_data(name,email,phone);
return Py_BuildValue(""); /* returns Python's None data type */
}
/* Method table mapping names to wrappers */
static PyMethodDef spammethods[] = {
{"gcd", spam_gcd, METH_VARARGS},
{"print_data", spam_print_data, METH_VARARGS | METH_KEYWORDS },
{NULL, NULL}
};
/* Module initialization function */
void initspam() {
Py_InitModule("spam", spammethods);
}