Contents

An extern function has no Haze contracts, cannot be pure, and operates on C types rather than managed values. Use FFI only when the language and standard library do not provide the capability, keep the extern surface small, and expose a checked Haze API on top.

When FFI Is Justified#

Situation FFI appropriate Reason
A platform API has no standard-library wrapper Yes The capability is outside the language
An existing C library implements the required algorithm Yes, if adopting it is cheaper than reimplementing Interoperation is the point
A binary ABI must be matched exactly Yes The layout and calling convention are the specification
A Haze library already provides the operation No Use the library
The C version is assumed to be faster No Measure first
The author prefers C syntax No The program loses contracts, safety, and portability
A temporary shortcut to avoid designing a Haze type No The shortcut becomes permanent

A performance argument is credible only after measurement.

Boundary Shape#

A good boundary has three layers: the extern declaration, a conversion layer, and a public Haze function with contracts, precise types, and Result errors.

extern (C) getenv(name cstr) cstr = "getenv"

type EnvError =
    | Missing(name str)
    | Invalid(name str)

fn require_env(name str) Result[str, EnvError] {
    const value = getenv(cstr::from_str(name))
    if cstr::is_null(value) {
        return Error(Missing(name))
    }
    return match cstr::to_str(value) {
        Success(text) => Success(text)
        Error(_) => Error(Invalid(name))
    }
}

The extern declaration is private. require_env takes a Haze string, returns a Haze Result, and names its error cases. A caller never sees a cstr or a null pointer.

Extern Functions#

extern (C) abs(x i32) i32 = "abs"
extern (C) puts(text cstr) i32 = "puts"
extern (C) getpid() i32 = "getpid"

Only extern (C) is supported. An omitted return type means void. The symbol string is required. Extern functions cannot have a body, contracts, generic parameters, or pure, and cannot be used as values.

The compiler cannot fold an extern call. The wrapper must validate the result and translate it into a Haze type.

Extern Records#

A C-layout struct is declared with extern in the type body.

type DivResult extern {
    quot i32
    rem i32
}

extern (C) div(num i32, den i32) DivResult = "div"

Fields must be scalar, ptr, or cstr. Managed types are not allowed. Extern records cannot be generic or declare invariants. They are copied by value, matching C semantics.

Extern values cannot appear inside ordinary records, sum variants, or lists.

type Pair extern {
    left  i32
    right i32
}

fn sum(pair Pair) i32 => pair.left + pair.right

A function that needs a collection of C-layout values should copy them into Haze records at the boundary.

C Strings and Pointers#

cstr is a nullable pointer to a null-terminated byte sequence. cstr::from_str creates a view of a Haze string, cstr::to_str returns Result[str, CStrError], and cstr::is_null tests for null.

const value = getenv(cstr::from_str("HOME"))
if !cstr::is_null(value) {
    match cstr::to_str(value) {
        Success(text) => print(text)
        Error(_) => print("invalid UTF-8")
    }
}

ptr is an opaque pointer. It supports equality and ptr::add. There is no dereference syntax and no pointer arithmetic operator.

The lifetime of a C pointer is not tracked. If a C function returns memory the caller must free, the wrapper must document ownership and expose a Haze API that frees it. If a C function retains a pointer, the wrapper must ensure the pointee outlives the retention.

Linking#

Additional libraries are passed with -l and search directories with -L.

hz app.hz -L/usr/local/lib -lexample

The default is static linking. -d requests dynamic linking. On Unix, -lm is added automatically. The runtime archive is found next to the compiler, through HAZE_RUNTIME, or through -runtime. See Command-Line Tool.

Platform Variation#

Use @cfg to select declarations by platform.

@cfg(family == unix)
extern (C) getuid() u32 = "getuid"

@cfg(family == windows)
fn user_id() u32 => 0

The condition is evaluated at compile time. See Conditional Compilation.

Boundary Rules#

Rule Reason
Keep extern declarations private Callers should depend on the Haze API, not the C ABI
Convert to Haze types immediately Managed values and contracts do not cross the boundary
Return Result for foreign failures C error codes and null pointers are expected failures
Validate lengths and ranges before the call The C function will not check Haze preconditions
Document ownership of returned pointers Haze does not track foreign lifetimes
Do not expose cstr or ptr in a public signature They leak an unmanaged representation
Wrap platform variation in @cfg A single declaration is rarely portable
Do not pass managed values through an opaque pointer The collector cannot see the foreign use
Measure before claiming a performance benefit Calls and marshalling have costs

Wrapper Checklist#

Question Required answer
Is the capability unavailable in Haze? Yes, or use the Haze library
Is the extern declaration private? Yes
Does the public function take and return Haze types? Yes
Are foreign errors translated to Result? Yes
Are null, length, and range checks performed? Yes
Is pointer ownership documented and enforced? Yes
Is platform variation handled with @cfg? Yes, where needed
Is the wrapper tested on every supported platform? Yes
Is the FFI isolated in a module with a small surface? Yes

Cost#

The boundary gives up contracts, purity, managed values, and the Haze memory model. A program can still use FFI well by treating the boundary as a small, tested adaptor and keeping the rest of the program in Haze. The mistake is letting the C representation leak into the domain.

Summary#

Layer Responsibility Example
Extern declaration Name the symbol and the C signature extern (C) getenv(name cstr) cstr = "getenv"
Conversion Translate between C and Haze representations cstr::to_str
Checked API State contracts, return Result, hide raw types require_env(name str) Result[str, EnvError]