Definition
A foreign function interface (FFI) is a mechanism with which code written in one programming language calls functions written in another, usually functions compiled from C into machine code. ctypes is the FFI in Python’s §12.23 standard library. It loads a shared library, a file of compiled functions that a program can load while it runs, lets the programmer state the C type of each argument and result, and converts values at each call. FFI names the general mechanism; ctypes is one implementation, and it cannot read C header files.
The idea
A Python program must drive a device through a vendor’s library compiled from C. A C function expects each argument in a particular processor register or stack slot, with a particular width, as fixed by the ABI §12.47 (application binary interface), the machine-level rules for calls. A Python integer is an object of any size. ctypes converts between the two, but it knows only what the programmer declared; where nothing is declared, it treats integer arguments and the result as C int values.
ctypes is an interpreter at a border. On the Python side, the language checks types and frees memory automatically; on the C side, nothing checks anything. A wrong declaration is a mistranslation that the interpreter cannot notice, because it has no copy of the original. A buffer handed across is a lent book: if the owner throws it away while the borrower still reads it, the borrower reads whatever now lies there. The picture stops at the consequences: a mistake at this border can corrupt the whole Python process, with no exception raised.
How it works
Calling a C function from Python takes five steps:
Load:
lib = ctypes.CDLL("libdev.so"). The operating system’s dynamic linker §12.49 maps the file into the process.CDLLuses the standard C calling convention, the rule for where arguments go and who cleans up after a call; on Windows,ctypes.WinDLLuses thestdcallconvention of many Windows functions.Declare:
lib.dev_read.argtypes = [ctypes.c_void_p, ctypes.c_size_t]andlib.dev_read.restype = ctypes.c_int. Types such asc_int32,c_doubleandc_void_p, a pointer of unspecified target type, name C types; a subclass ofctypes.Structuremirrors a C structure.Provide memory:
buf = ctypes.create_string_buffer(64)allocates 64 writable bytes owned by the Python objectbuf. A Pythonbytesobject passed as achar *hands over memory that the C function must not change.Call:
lib.dev_read(buf, 64). ctypes converts each argument according toargtypes, releases the GIL (global interpreter lock), the lock that lets only one thread run Python code at a time, calls the function, takes the lock back, and converts the result according torestype.Callbacks §14.22:
ctypes.CFUNCTYPEwraps a Python function so that C code can call it through a function pointer.
Two defaults cause most errors. Without restype, ctypes assumes that the result is a C int, which is 32 bits on the usual 64-bit platforms. Without argtypes, ctypes passes Python integers as C int, cutting each value to fit, passes bytes and str objects as pointers, and refuses other objects, such as floating-point numbers §4.49, with an ArgumentError.
A wrong declaration does damage in one of three ways. A wrong width or type changes the value that crosses: high bits are cut off, or a sign is misread. A wrong calling convention makes the callee read its arguments from the wrong places, or unbalances the stack. A wrong lifetime lets native code use memory that Python has already freed, a use-after-free §4.6. On 64-bit platforms each operating system has one main calling convention, so convention mistakes arise mainly on 32-bit Windows, with functions that take a variable number of arguments, and with callbacks. The damage often appears later and elsewhere.
Worked example
On a 64-bit Linux system, a C function declared as void *dev_open(void) returns the address 0x00007f12b4560010, which is 139,718,311,673,872. The Python code sets no restype, so ctypes reads the result as a 32-bit signed C int and keeps the low 32 bits, 0xb4560010, which is 3,025,534,992. Their top bit is 1, so as a signed number the value is . The lost part is , and indeed . When the program passes back to dev_close, the function receives an address with the wrong high 32 bits and touches memory that was never its object. The repair is lib.dev_open.restype = ctypes.c_void_p and lib.dev_close.argtypes = [ctypes.c_void_p].
A library function dev_read_async(buf, n, done) starts a read and returns at once; when the data arrive, its own thread writes n bytes into buf and then calls done. A Python function creates a 64-byte buffer with create_string_buffer and a callback object with CFUNCTYPE, starts the read at 0 ms and returns at 0.1 ms. CPython, the standard Python implementation, uses reference counting §9.22: it frees an object as soon as the last reference to it disappears. At 0.1 ms, therefore, both the buffer and the callback object are freed. At 5 ms the library writes 64 bytes into memory that Python may already have reused, then calls through a function pointer into freed memory. The repair is to keep references to the buffer and the callback object, for example in a dictionary keyed by request, until done has run. The ctypes documentation gives the same warning for callbacks.
Stated precisely
A call through ctypes is correct only if six conditions hold.
Signature: each declared argument type and the result type have the same size, signedness and kind (integer, floating point, pointer or structure) as the C declaration on this platform, and a function with a variable number of arguments is called as one.
Convention: the calling convention ctypes uses (
CDLLorWinDLL, andCFUNCTYPEorWINFUNCTYPEfor callbacks) is the function’s own.Layout: each
Structurehas the C structure’s field order, sizes, alignment §4.22 and padding.Extent: every pointer points to memory at least as large as the callee may access through it.
Object lifetime §4.1: that memory stays allocated, and is not reused, from the call until the callee’s last access, which may come after the call returns, as in asynchronous completion §9.28, and is marked by a documented completion event.
Ownership: memory that the library allocates is released only by the function the library names for that purpose.
If any condition fails, the program has undefined behavior §4.12: the rules of C impose no requirement on what happens next, anywhere in the process.
For widths: an integer cut to bits becomes ; read as a signed number, a result means . In the example, and , which is at least , so it is read as negative.
Limits and common mistakes
Declaring types is not checking them. ctypes trusts argtypes and restype completely, so a declaration that disagrees with the library goes undetected. The separate cffi library, in its mode that compiles a small C extension module, lets the C compiler check declarations against the real header; it does not prevent lifetime errors.
Python’s memory safety ends at the boundary. A native crash ends the process, and no try block catches it; the standard module faulthandler can print the Python stack when it happens.
ctypes is not a sandbox §2.30: native code runs with every right of the Python process.
Because ctypes releases the GIL during a call, native code can run while other Python threads run. A library that is not safe to call from several threads at once needs a lock on the Python side.
The C variable errno, through which many C functions report the cause of an error, must be read with use_errno=True and ctypes.get_errno(), because later work in the interpreter §2.13 can overwrite it.
Questions answered
What happens if an argument width, calling convention, or buffer lifetime is wrong?
The program has undefined behavior, and Python cannot catch it: the result ranges from a silently wrong value to corrupted memory or a crash of the whole Python process. Each mistake works differently.
A wrong argument or result width changes the value that crosses the boundary: high bits are cut off or a sign is misread. A 64-bit address returned through the default 32-bit
intresult type of ctypes becomes a different number, and using it as an address touches the wrong memory.A wrong calling convention makes the callee read its arguments from the wrong places, or leaves the stack unbalanced. On 32-bit Windows, ctypes detects an unbalanced stack and raises
ValueError; in general, no check exists.A wrong buffer lifetime lets native code read or write memory that Python has already freed and may have reused, a use-after-free, often long after the call returned.
The defenses are to declare argtypes and restype exactly as the C header states, to use the library’s calling convention, to keep every buffer and callback object referenced until the library’s documented completion event, and to treat the native library as code that runs with every right of the Python process.
Related entries: Native application binary interface (ABI) (§12.47), Ownership (§4.2), Use-after-free (§4.6), Overflow-safe range check (§4.17), Guest-host ABI (§2.37), Object lifetime (§4.1), Truncation and extension (§4.19), Asynchronous completion (§9.28), Reference counting (§9.22), Undefined behavior (UB) (§4.12). Further reading: [64].