Python Language Writing extensions Hello World with C Extension


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>

#define IS_PY3K

static PyObject *hello_greet(PyObject *self, PyObject *args)
    const char *input;
    if (!PyArg_ParseTuple(args, "s", &input)) {
        return NULL;
    printf("%s", input);

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);
PyMODINIT_FUNC inithello(void)
    (void) Py_InitModule("hello", HelloMethods);

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

import hello          # imports the compiled library
hello.greet("Hello!") # runs the greet() function with "Hello!" as an argument