std.ffi

Byte transfers and resource ownership at C boundaries.

Importuse std.ffi

Types

struct OwnedPtr#

Checked ownership of a foreign pointer from std.ffi.own or own_with. Register defer ffi.release(resource) or transfer its cleanup obligation.

An opaque handle: only std.ffi can produce one, and its contents are not reachable from moon source.

use std.ffi
use std.ffi.OwnedPtr

extern fn acquire_resource() -> *void

fn main() {
  let resource: OwnedPtr = ffi.own(acquire_resource()).unwrap()
  defer ffi.release(resource)
  let borrowed = ffi.borrow(resource).unwrap()
  println(borrowed as int)
  println(ffi.is_released(resource))
}
_handle: NativeHandle

The native resource.

Functions

fn own(*void) -> Result<OwnedPtr, Error>#

Transfers a non-NULL foreign allocation beginning with MoonFfiOwnedHeader into an OwnedPtr with one cleanup obligation. Register defer ffi.release(owner) or transfer that obligation. Invalid headers and unsafe destructor flags return a named error; ownership remains with the caller on failure.

fn own_with<T>(pointer: *T, destructor: fn(*T) -> void) -> Result<OwnedPtr, Error>#
fn borrow(OwnedPtr) -> Result<*void, Error>#

Borrows the live foreign pointer. The returned pointer retains its owner through ordinary and @blocking extern calls; borrowing after release returns Released.

fn is_released(OwnedPtr) -> bool#

Reports whether release has been requested for this shared owned pointer.

fn release(OwnedPtr)#

Releases an owned foreign allocation idempotently. An active native call defers destruction until its borrow ends.

fn release_callback(fn(int) -> void)#

Stops retaining a queued callback after the foreign API has stopped invoking it. Repeated release is safe.

fn queued_dropped() -> int#

Cumulative queued-callback calls dropped because a callback's bounded inbox was full.

fn copy_from_c(*void, int, int) -> string#

Copies len bytes at ptr + offset into a moon string in one bulk memcpy (byte-faithful, embedded NULs preserved). A NULL pointer or zero length yields ""; a negative length is an error. The caller must ensure the range is readable.

fn copy_to_c(*void, int, string)#

Copies a moon string's bytes to ptr + offset in one bulk memcpy. A NULL pointer is a no-op. The caller must ensure the destination range is writable.

fn read_cstr(*void, int) -> string#

Reads the NUL-terminated C string at ptr + offset into a moon string (the NUL is not included). A NULL pointer yields "". The caller must ensure the string is NUL-terminated.