The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes simultaneously in multi-threaded applications.
CPython allows extending Python functionality by writing C/C++ extensions, which can provide performance benefits for CPU-intensive tasks and access to low-level system calls.
ctypes
for C Extensions:
ctypes
module allows calling functions in shared libraries and using C data types directly from Python code without compiling C code into a Python extension module.Example using ctypes
to load and use a C library:
import ctypes
# Load the C library
libc = ctypes.CDLL('libc.so.6')
# Call a function from the C library
libc.printf(b"Hello from C!\n")
Python.h
) to define new types, functions, and modules that can be imported and used in Python scripts.#include <Python.h>
static PyObject *example_func(PyObject *self, PyObject *args) {
const char *input;
if (!PyArg_ParseTuple(args, "s", &input)) {
return NULL;
}
printf("Received: %s\n", input);
return Py_None;
}
static PyMethodDef ExampleMethods[] = {
{"example_func", example_func, METH_VARARGS, "Prints a string from Python"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef examplemodule = {
PyModuleDef_HEAD_INIT,
"examplemodule",
NULL,
-1,
ExampleMethods
};
PyMODINIT_FUNC PyInit_examplemodule(void) {
return PyModule_Create(&examplemodule);
}
Python’s memory model and object lifecycle manage how Python allocates, uses, and releases memory for objects.
Memory Management:
malloc
and free
).Object Lifecycle: