Python Ctypes Module
The ctypes module is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
Importing the Module
import ctypes
Loading Shared Libraries
You can load shared libraries (DLLs on Windows, .so files on Linux) using ctypes.CDLL or ctypes.WinDLL.
import ctypes
import os
# Load the C standard library (example for Windows)
if os.name == 'nt':
libc = ctypes.CDLL("msvcrt.dll")
else:
# Example for Linux
libc = ctypes.CDLL("libc.so.6")
Calling Functions
Once loaded, you can call functions from the library like normal Python functions. Note that C functions often require bytes strings instead of Python strings.
libc.printf(b"Hello, %s\n", b"World")
Data Types
ctypes provides a number of primitive C compatible data types.
ctypes.c_int: Represents a C signed int.ctypes.c_float: Represents a C float.ctypes.c_char_p: Represents a C char * (string).ctypes.c_void_p: Represents a C void *.
i = ctypes.c_int(42)
print(i.value) # Output: 42
Structures
You can define C structures and unions by subclassing ctypes.Structure and ctypes.Union.
class Point(ctypes.Structure):
_fields_ = [("x", ctypes.c_int),
("y", ctypes.c_int)]
point = Point(10, 20)
print(f"Point: ({point.x}, {point.y})")