Python C Library
How many ways Python can interact with C libraries?
Two. There are two different modes totally.
ctypes
to load any dynamic library from a C librariesimport module
to import a dynamic library written using the Python C API
Let's clarify the terminology a bit:
ctypes
to Load Dynamic Libraries (including any C library):
ctypes
is a foreign function interface (FFI) library in Python that allows you to call functions from dynamic/shared libraries written in languages like C.- It can be used to load and call functions from C libraries (or any dynamic/shared libraries), and it's a more manual, low-level approach to interfacing with C code.
- Example with
ctypes
:
import module
for Dynamic Libraries written in Python C API:- If a C library is written using the Python C API and compiled as a Python extension module (
.pyd
on Windows or.so
on Unix-like systems), you can use the import statement toimport
and use it in Python. - This
Pythonic
approach typically provides a more seamless integration as it allows the C code to be treated as a native Python module. - Example with
import module
:
- If a C library is written using the Python C API and compiled as a Python extension module (
What's the file's name that Python look for when using import module
to import C API libraries?
Python will look for a shared library with a suitable name, as determined by the platform conventions.
The shared library could be named something like libexample.so
on Unix-like systems or example.dll
on Windows. The PyInit_example
function initializes the module.
Python int
object
Python uses a variable-size integer representation,
Overhead size
: 24 bytes, including Python header objectData size
: 4 or 8 bytes, storing smallerint
using 4 bytes and biggerint
using 8 bytes.
>>> sys.getsizeof(0x560f7ab1e1c0)
32
>>> sys.getsizeof(0xc0)
28