The following C source file (which we will call hello.c
for demonstration purposes) produces an extension module named hello
that contains a single function greet()
:
#include <Python.h>
#include <stdio.h>
#if PY_MAJOR_VERSION >= 3
#define IS_PY3K
#endif
static PyObject *hello_greet(PyObject *self, PyObject *args)
{
const char *input;
if (!PyArg_ParseTuple(args, "s", &input)) {
return NULL;
}
printf("%s", input);
Py_RETURN_NONE;
}
static PyMethodDef HelloMethods[] = {
{ "greet", hello_greet, METH_VARARGS, "Greet the user" },
{ NULL, NULL, 0, NULL }
};
#ifdef IS_PY3K
static struct PyModuleDef hellomodule = {
PyModuleDef_HEAD_INIT, "hello", NULL, -1, HelloMethods
};
PyMODINIT_FUNC PyInit_hello(void)
{
return PyModule_Create(&hellomodule);
}
#else
PyMODINIT_FUNC inithello(void)
{
(void) Py_InitModule("hello", HelloMethods);
}
#endif
To compile the file with the gcc
compiler, run the following command in your favourite terminal:
gcc /path/to/your/file/hello.c -o /path/to/your/file/hello
To execute the greet()
function that we wrote earlier, create a file in the same directory, and call it hello.py
import hello # imports the compiled library
hello.greet("Hello!") # runs the greet() function with "Hello!" as an argument