Atom

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.

Atom
use ffi
buffer = ffi.alloc(4)
try:
    print(type(buffer) == ptr)
finally:
    ffi.free(buffer)
Output
true

The result is a native pointer. Release it even if a later operation raises.

  • A cstring parameter 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 returned cstring is copied or becomes null. Use a ptr return 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.free releases 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 as ptr, and index its first element after the call.
  • Packed storage passed directly as ptr is borrowed and pinned for the call only. Use ffi.address to pin explicitly if the native code retains the address. Release the pin with ffi.free once the native user has stopped. Keep enough bytes for all C accesses and check layout/alignment before exposing storage.
  • ffi.symbol and 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.free is 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.callback returns 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.