9. Python C Extensions

These examples demonstrate creating Python extensions in C for tasks requiring performance optimizations, such as mathematical computations, array processing, and string manipulations.


1. Simple "Hello, World!" C Extension

C Code (hello.c):

#include <Python.h>

static PyObject* hello_world(PyObject* self, PyObject* args) {
    printf("Hello, World!\n");
    Py_RETURN_NONE;
}

static PyMethodDef HelloMethods[] = {
    {"hello_world", hello_world, METH_VARARGS, "Prints Hello, World!"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef hellomodule = {
    PyModuleDef_HEAD_INIT,
    "hello",
    NULL,
    -1,
    HelloMethods
};

PyMODINIT_FUNC PyInit_hello(void) {
    return PyModule_Create(&hellomodule);
}

Python Setup Script (setup.py):

Build and Install:

Python Usage:


2. Adding Two Numbers

C Code (add.c):

Python Usage:


3. Computing Factorial

C Code (factorial.c):


4. String Reversal


5. Dot Product of Two Arrays


6. Finding Maximum Value in an Array


7. Summing an Array


8. Converting Fahrenheit to Celsius


9. Matrix Multiplication


10. Simple Linear Search


Last updated