Sub topic 13
The C data interface: handing arrays between libraries
This chapter assumes you know what an Arrow array, schema, and buffer are, and that you can run Python with pyarrow 15 or later installed. You should also be able to read a short C struct definition. You don't need to write C.
The problem it solves
Two libraries can both "use Arrow" and still be unable to share data. Suppose a Rust library and a Python library each link their own copy of the Arrow implementation. Their C++ or Rust classes are incompatible, so one cannot hand an Array object to the other.
The Arrow C data interface fixes this with a few plain C structs. A library that can read and write these structs can exchange columns with any other library that can, with no dependency on a particular Arrow implementation. The buffers are not copied. Only a small struct of pointers moves.
The interface has three parts:
ArrowSchemadescribes a type.ArrowArraydescribes the data for one array.ArrowArrayStreamyields a sequence of record batches.
The two core structs
The definitions below are the ones the Arrow specification gives. Libraries copy them into their own source. They don't link a shared header.
struct ArrowSchema {
const char* format;
const char* name;
const char* metadata;
int64_t flags;
int64_t n_children;
struct ArrowSchema** children;
struct ArrowSchema* dictionary;
void (*release)(struct ArrowSchema*);
void* private_data;
};
struct ArrowArray {
int64_t length;
int64_t null_count;
int64_t offset;
int64_t n_buffers;
int64_t n_children;
const void** buffers;
struct ArrowArray** children;
struct ArrowArray* dictionary;
void (*release)(struct ArrowArray*);
void* private_data;
};The structs carry what you already know from the earlier chapters on buffers and schemas.
- Type:
formatis a short string."i"is int32,"l"is int64,"u"is a UTF-8 string,"+s"is a struct, and"+l"is a list. Nested types usechildren. - Data:
buffersis an array of raw pointers. For a nullable int32 array, the first pointer is the validity bitmap and the second is the values. A string array has three: validity, offsets, and bytes. - Slicing:
offsetlets a consumer see a slice of the buffers without copying them. A consumer that readsbuffersdirectly must addoffsetto every index it computes. - Nulls:
null_countmay be-1, which means "not computed yet".
The type lives in ArrowSchema and the data in ArrowArray, so you always move them as a pair.
Ownership: the release callback
Pointers with no clear owner are dangerous, so the interface defines ownership precisely. Each struct carries a release function pointer. The rules are:
- The producer allocates the struct and fills it in.
- The consumer takes ownership by moving the struct into its own memory. It then marks the original as released by setting
releasetoNULL. - When the consumer finishes, it calls
releaseexactly once. The callback frees the buffers, or lowers a reference count on them. - After
releaseruns, nothing may read the buffers.
A struct with release == NULL has been released or moved and must not be used. This is how a consumer tells a live struct from a dead one. Because the callback is a function pointer supplied by the producer, the consumer can free memory it did not allocate. It never needs to know which allocator the producer used.
The next diagram shows one handoff.
The stream interface
A single ArrowArray is one chunk. Most real exchanges involve many batches, such as a query result that arrives in pieces. ArrowArrayStream covers that case with a struct of callbacks:
struct ArrowArrayStream {
int (*get_schema)(struct ArrowArrayStream*, struct ArrowSchema* out);
int (*get_next)(struct ArrowArrayStream*, struct ArrowArray* out);
const char* (*get_last_error)(struct ArrowArrayStream*);
void (*release)(struct ArrowArrayStream*);
void* private_data;
};The consumer calls get_schema once. It then calls get_next repeatedly until the callback returns an array whose release is NULL, which signals the end of the stream. Each call returns a nonzero error code on failure, and get_last_error gives the message. A stream is a good fit for results that are larger than memory. The producer can compute batch n+1 while the consumer works on batch n.
Using it from Python: PyCapsules
Python code rarely touches raw structs. The standard Python route is the Arrow PyCapsule interface, a set of dunder methods that return the C structs wrapped in PyCapsule objects:
| Method | Returns | Meaning |
|---|---|---|
| `__arrow_c_schema__()` | one capsule | an `ArrowSchema` |
| `__arrow_c_array__()` | two capsules | an `ArrowSchema` and an `ArrowArray` |
| `__arrow_c_stream__()` | one capsule | an `ArrowArrayStream` |
A capsule's destructor releases the struct if nobody consumed it. This prevents leaks when a capsule is created but never used.
The first example exports an array and imports it again.
import pyarrow as pa
arr = pa.array([1, None, 3], type=pa.int32())
schema_capsule, array_capsule = arr.__arrow_c_array__()
print(type(schema_capsule).__name__)
print(type(array_capsule).__name__)
# Underscore-prefixed: meant for library authors, not everyday code.
imported = pa.Array._import_from_c_capsule(schema_capsule, array_capsule)
print(imported)
print(imported.null_count)The import moves the structs out of the capsules, and the original capsules are then spent. Do not import the same pair twice.
In practice you rarely call these methods yourself. A library that accepts Arrow data checks for __arrow_c_stream__ on its input, and a library that produces Arrow data defines the method. Any library on one side then works with any on the other. This example makes a class that exposes a table through the stream protocol, then reads it with pa.table:
import pyarrow as pa
class TableProducer:
"""A stand-in for any library that can export Arrow data."""
def __init__(self, table):
self._table = table
def __arrow_c_stream__(self, requested_schema=None):
return self._table.__arrow_c_stream__(requested_schema)
source = pa.table({"id": [1, 2, 3], "name": ["a", None, "c"]})
received = pa.table(TableProducer(source))
print(received.schema)
print(received.num_rows)
print(received.equals(source))TableProducer knows nothing about the consumer. pa.table knows nothing about TableProducer. They agree only on the method name and the struct layout. The requested_schema argument lets a consumer ask for a compatible type, such as large_string instead of string. The producer may honor the request or ignore it, and the consumer must check the schema it actually receives.
Zero-copy and its limits
The handoff moves only the structs, so the buffers are shared by reference. For large columns this removes the serialization cost that other exchange paths pay. Three points qualify that:
- Lifetime is tied to
release. The consumer's view stays valid only until it callsrelease. If you keep a raw pointer past that point, you read freed memory. Libraries that wrap imported data, such as pyarrow, hold the release call until the wrapper object is garbage collected. - Zero-copy applies to the handoff, not to later work. If the consumer casts a type, converts to NumPy with nulls present, or builds a pandas
objectcolumn, it allocates and copies. The interface guarantees only that the handoff itself copies nothing. - Pointers are meaningful only inside one process. The structs hold memory addresses, so you can't send them through a socket or write them to disk. For that you need the IPC format, Flight, or ADBC, which later chapters cover.
Common errors
- Using a struct after moving it. Check
release != NULLbefore reading. In Python, avoid reusing capsules. - Forgetting to release. In C, C++, or Rust code that handles raw structs, a missing
releasecall leaks the producer's buffers. Python capsules protect you from this, and raw pointers do not. - Ignoring
offset. A sliced array shares its parent's buffers. Readingbuffers[1][0]instead ofbuffers[1][offset]returns the wrong value. - Assuming
null_countis accurate. A value of-1means unknown. Count the bits in the validity bitmap if you need the real figure. - Mixing up the two Arrow worlds. Two copies of Arrow in one process do not share memory pools or object types. The C interface is the safe boundary between them.
Choosing this mechanism
Use the C data interface when two libraries run in the same process and you want to avoid a copy or a hard dependency on one Arrow build. Typical cases are a Python wrapper over a Rust or C++ engine, or passing a DataFrame between query libraries. Use IPC, Flight, or ADBC when the data crosses a process or machine boundary.
Exercise
A consumer imports an ArrowArray from a producer, reads it, and finishes. It then forgets to call release on the struct, and it keeps no other reference to the data. What goes wrong, and why can the consumer call release on memory it never allocated?
Show answer
The producer's buffers are never freed, so the process leaks memory. Ownership moved to the consumer when it took the struct, so releasing it was the consumer's job. The consumer can free memory it did not allocate because the producer supplies the release callback. The callback knows how to free the producer's buffers, or how to drop a reference to them, whatever allocator was used.
Exercise
You export a pyarrow table with _arrowcstream_ and want to send the result to a service in another process. Why is passing the capsule or its pointers not enough, and what should you use instead?
Show answer
The structs contain memory addresses that are valid only inside the exporting process, and the buffers they point to do not travel with them. You need a format that carries the bytes, such as the Arrow IPC stream format, Arrow Flight, or ADBC.