An in-process call still crosses a contract boundary
A foreign function interface lets one language call code implemented in another language or native library. Sharing a process does not automatically share type, memory-management, and exception rules. A Python integer still needs a defined C representation, and a pointer does not independently establish the length of its backing array. Those facts belong in the boundary contract.
This guide uses Linux, Python 3.12, and C11. C computes a sum while Python owns both input and output storage. Read the ownership guide first so that storage responsibility and valid borrowing periods are familiar. The example was verified in a separate process using a disposable directory. Shared-library formats and calling conventions differ across platforms; the commands are not claimed to cover every operating system. A real integration must identify its ABI and library version as well.
Specify more than type names
The input is at most four uint32_t values, the result is uint64_t, and the element count is size_t. C borrows the input only for the duration of the call. It neither stores the pointer nor frees its storage. The caller also supplies output storage. Status zero means success, one rejects invalid pointer conditions, and two rejects an excessive count. Failure leaves the output unchanged.
The four-element limit keeps the example bounded and makes overflow reasoning simple: four uint32_t values fit in uint64_t. This is not an arbitrary-length aggregation API. Nor can C generally discover allocation capacity from a pointer and a count. A count below four is insufficient if the actual array is shorter. The caller must maintain valid storage of at least the stated length. Record type, capacity, and lifetime as distinct requirements.
| Storage | Owner and release responsibility | Native use |
|---|---|---|
| Input array | Python caller | Read only during the call |
| Output value | Python caller | Write during a successful call |
| Retained pointer | Not allowed by this API | No use after return |
Return status from the native side
Save this as sum_u32.c. Build it with gcc -std=c11 -O2 -Wall -Wextra -Werror -shared -fPIC sum_u32.c -o libsum_u32.so. The function checks the output pointer and count limit before reading. A nonempty input requires a non-null input pointer. It writes the result only after completing the loop, so its rejection paths preserve the output value.
These checks do not make arbitrary bad pointers detectable. A non-null pointer can still refer to freed or undersized storage. We do not execute inputs that invoke such undefined behavior. An implementation using C++ exceptions would additionally need a contract to catch and translate them within the boundary. This C example implements status returns, not cross-language exception propagation. The native error mechanism must be chosen deliberately rather than inferred from the calling language.
#include <stdint.h>
#include <stddef.h>
int sum_u32(const uint32_t *values, size_t count, uint64_t *out) {
if (out == NULL) return 1;
if (count > 4) return 2;
if (count > 0 && values == NULL) return 1;
uint64_t total = 0;
for (size_t i = 0; i < count; i++) total += values[i];
*out = total;
return 0;
}Declare widths and validate before conversion
Save the Python code beside the library as ffi_check.py and run python3.12 ffi_check.py. Explicit argtypes and restype declarations align input pointer, element count, output pointer, and status with the C declaration. An unspecified default return interpretation can differ from the function's actual declaration. Notice the distinction between fixed-width integers and size_t.
The wrapper validates Python integer ranges before conversion. Do not assume conversion to a fixed-width type provides the desired range policy. This API also excludes bool values, so it deliberately tests type(v) is int. Python variables keep the array and output alive until the borrowed call finishes. Tests cover ordinary values, a sum exceeding 32 bits, empty input, and rejected values. All assertions passed with Python 3.12.14 and GCC 13.3.0.
import ctypes as C
from pathlib import Path
lib = C.CDLL(str(Path('libsum_u32.so').resolve()))
lib.sum_u32.argtypes = [C.POINTER(C.c_uint32), C.c_size_t, C.POINTER(C.c_uint64)]
lib.sum_u32.restype = C.c_int
def checked_sum(values):
if len(values) > 4:
raise ValueError('at most four values')
if any(type(v) is not int or not 0 <= v <= 0xffffffff for v in values):
raise ValueError('uint32 values required')
array = (C.c_uint32 * len(values))(*values)
result = C.c_uint64(0)
status = lib.sum_u32(array, len(values), C.byref(result))
if status != 0:
raise RuntimeError('native status ' + str(status))
return result.value
assert checked_sum([1, 2, 3]) == 6
assert checked_sum([0xffffffff, 1]) == 4294967296
assert checked_sum([]) == 0
for bad in [[-1], [0x100000000], [True], [1, 2, 3, 4, 5]]:
try:
checked_sum(bad)
except ValueError:
pass
else:
raise AssertionError('invalid input accepted')
result = C.c_uint64(99)
assert lib.sum_u32(None, 1, C.byref(result)) == 1
assert result.value == 99
assert lib.sum_u32(None, 5, C.byref(result)) == 2
assert result.value == 99
print('FFI values, widths, and error contracts passed')Define release responsibility and retained lifetimes
Here Python manages both buffers and C never calls malloc or free. This deliberately removes allocator-pairing issues from the example. If a real API returns native-allocated storage, add which function releases it, when release is allowed, and how exactly one release is ensured. An arbitrary similarly named deallocator is not necessarily compatible with the allocation source.
An asynchronous API that retains a pointer cannot use the assumption that borrowing ends when the call returns. Storage and callbacks may need to remain alive until a completion notification. A moving collector may also require pinning or handles. The collector does not necessarily understand a reference retained only in external C code. A table of owner, borrower, final use, and release function exposes what must change when moving from a synchronous example to an asynchronous integration.
Strings and errors need their own conversion rules
For strings, specify whether the API takes bytes or text, which encoding it uses, and the unit of length. A null-terminated C string can end at an embedded zero; a length-delimited byte sequence can contain zero as data. Python character counts are not interchangeable with UTF-8 byte counts. A char in a type declaration does not settle these semantics.
Error conversion needs similar care. If an API uses errno, establish when it is set and how to retrieve it correctly immediately after the call. Mapping every nonzero value into one exception may erase distinctions between retryable failure and invalid input. Our example defines statuses one and two while the Python wrapper normally rejects those inputs first. Checks on both sides still have different responsibilities that should be explained separately.
An ABI is not a portable storage format
Using uint32_t does not make raw memory bytes a portable network or file representation. Byte order, structure padding, and alignment must be considered separately for a calling ABI and for persistent or transmitted data. This example passes an array within one process; it defines no wire format.
For external storage, choose a representation with explicit field widths, byte order, lengths, and versioning. Equal sizeof results alone do not establish compatibility across environments. Agreement between Python and C on the calling ABI and the ability to read saved data in a future environment require different tests. Treat persistence as another boundary: values are crossing machines or time rather than merely crossing a function call within the current process.
Exercise: change one boundary requirement
Explain why [4294967295, 1] produces 4294967296 rather than zero. The elements are 32-bit unsigned values, but accumulation and output use 64 bits. Next identify the exact precondition that rejects a negative value before entering C. Base the explanation on validation rather than guessing from a converted value.
Finally suppose C changes its contract and retains the input pointer. Can the local variables in checked_sum alone guarantee the required lifetime? No: a longer-lived owner and a completion protocol are needed. Renaming a Python variable cannot supply those requirements. Design the retention and completion API instead. Only the combination of declarations, lengths, ownership, completion, and error rules provides a complete account of the language boundary.