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):
Copy
#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):
Copy
Build and Install:
Copy
Python Usage:
Copy
2. Adding Two Numbers
C Code (add.c):
Copy
Python Usage:
Copy
3. Computing Factorial
C Code (factorial.c):
Copy
4. String Reversal
Copy
5. Dot Product of Two Arrays
Copy
6. Finding Maximum Value in an Array
Copy
7. Summing an Array
Copy
8. Converting Fahrenheit to Celsius
Copy
9. Matrix Multiplication
Copy
10. Simple Linear Search
Copy
Last updated