Ownership and call boundaries
Allocate and release a native buffer
Memory allocated through ffi.alloc belongs to the caller. Release it once when native code no longer needs the pointer.
use ffi
buffer = ffi.alloc(4)
try:
print(type(buffer) == ptr)
finally:
ffi.free(buffer)
true
The result is a native pointer. Release it even if a later operation raises.
- A
cstringparameter uses the Atom string's UTF-8 buffer for the call or encodes a char as a temporary C string. Embedded NUL is rejected. Pass null for a C null pointer. Treat the supplied storage as read-only. A returnedcstringis copied or becomes null. Use aptrreturn and the C library's release function when the API transfers ownership. A copied string does not release its C source. ffi.alloc(count)allocates zeroed native memory.ffi.freereleases it. Do not use the address after release. To read a C out parameter directly in Atom, create a one-element packed buffer of the corresponding type, pass it asptr, and index its first element after the call.- Packed storage passed directly as
ptris borrowed and pinned for the call only. Useffi.addressto pin explicitly if the native code retains the address. Release the pin withffi.freeonce the native user has stopped. Keep enough bytes for all C accesses and check layout/alignment before exposing storage. ffi.symboland ordinary C pointer returns are borrowed pointer wrappers. Use the documented release function of the foreign API if it returns owned memory or a handle.ffi.freeis for allocations, pins and callbacks acquired through Atom's own FFI API. Keep the library open while any binding, handle, opaque symbol address or native operation can still need it.ffi.callbackreturns executable native code tied to its VM. Reentry works during an active synchronous FFI call on the original thread in that VM. An invocation outside that context returns a zero value. Pointer arguments received by a callback are borrowed. Retain them only when the native API guarantees the referenced storage outlives the callback. Callback failure returns zero to C and becomes an Atom error when the native call returns. Unregister the callback on the native side before freeing the pointer. Hold a strong reference to the pointer the entire time C might call it. Executable memory restrictions can prevent creation. Coroutines cannot yield through this native boundary.- Atom checks what it can before crossing into C. The foreign library can read or write process memory and can block without observing Atom's cancellation or instruction limits. Match function signatures, allocation sizes, array lengths, storage mutability and ownership to the native API.