Extern and C FFI
Declaring C functions and records, ABI mapping, pointer conversions, linking, and restrictions.
Contents
Haze interoperates with C through extern (C) declarations and C-layout records. The surface is deliberately small. It exists for platform APIs, existing libraries, and ABIs that must be matched, not as a general-purpose escape hatch from the language.
Extern Functions#
An extern function declares the C symbol, the parameter types, and the return type.
extern (C) abs(x i32) i32 = "abs"
extern (C) puts(text cstr) i32 = "puts"
extern (C) getpid() i32 = "getpid"
The syntax is extern (C) name(params) ReturnType = "symbol". The return type is optional; if = follows the parameter list, the return type is void. Only the C calling convention is accepted. The symbol string is required.
An extern function cannot have a body, a contract, a generic parameter, or the pure modifier. It cannot be used as a first-class function value. These restrictions follow from the fact that the compiler does not know the function's effects, its domain, or its guarantee.
extern (C) sqrt(value f64) f64 = "sqrt"
A wrapper should validate the domain, call the extern, convert the result, and expose a Haze signature.
Extern Records#
A C-layout struct is declared with the extern keyword in the type body.
type DivResult extern {
quot i32
rem i32
}
extern (C) div(num i32, den i32) DivResult = "div"
Extern records cannot declare type parameters and cannot declare invariants. Their fields must be scalar, ptr, or cstr. Managed types such as List, records, sums, and Option are rejected. Extern values are not allowed inside ordinary records, sum variants, or lists.
Extern records use C size and alignment. They are copied by value when stored in a local or passed by value. Mutating a local copy does not affect the original, which matches C's value semantics but differs from an ordinary Haze record, which is a managed reference.
fn sum(value DivResult) i32 => value.quot + value.rem
C ABI Mapping#
| Haze type | C ABI representation |
|---|---|
i8 |
Signed 8-bit |
u8 |
Unsigned 8-bit |
i16 |
Signed 16-bit |
u16 |
Unsigned 16-bit |
i32, u32, bool |
32-bit word |
i64, u64, ptr, cstr |
64-bit word |
f64 |
Double |
| Extern record | C aggregate layout |
A normal Haze function uses the Haze internal ABI. An extern call uses the C ABI mapping above. The compiler emits the conversion at the call site; the source-level types are still the Haze types.
C Strings#
cstr is a nullable pointer to a null-terminated byte sequence. It is the type for C string parameters.
| Operation | Result | Meaning |
|---|---|---|
cstr::from_str(text) |
cstr |
View a Haze string as a C string |
cstr::from_ptr(pointer) |
cstr |
Reinterpret a raw pointer |
cstr::to_str(value) |
Result[str, CStrError] |
Validate and convert to a Haze string |
cstr::to_bytes(value) |
Result[bytes, CStrError] |
Convert to a byte buffer |
cstr::is_null(value) |
bool |
Test for a null pointer |
cstr::null() |
cstr |
The null C string |
CStrError has NullPointer and InvalidUtf8. A conversion should handle both. A cstr comparison with == compares addresses, not contents; convert to str when content equality is intended.
Raw Pointers#
ptr is an opaque address. It supports equality and a small set of helpers.
| Operation | Result | Meaning |
|---|---|---|
ptr::null() |
ptr |
The null pointer |
ptr::add(pointer, offset) |
ptr |
Advance by a byte offset |
ptr::from_cstr(value) |
ptr |
Reinterpret a C string as a pointer |
bytes::ptr(value) |
ptr |
Pointer to the byte buffer's storage |
There is no dereference syntax and no pointer arithmetic operator. The helpers are the entire surface. A pointer does not carry a length or a lifetime; the wrapper is responsible for both.
Calling and Linking#
The compiler uses a C compiler to assemble and link the generated code. A library is linked with -l and a search directory 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 -runtime, or through HAZE_RUNTIME.
A cross-target build also needs a C compiler for the target. The -cc flag selects the compiler, and the -target flag selects the ABI.
Platform Variation#
A foreign API that differs by platform should be selected with @cfg rather than hidden behind a single declaration that only works on one system.
@cfg(family == unix)
extern (C) getuid() u32 = "getuid"
@cfg(family == windows)
fn user_id() u32 => 0
The unused declaration is removed at parse time and is not type-checked. The Conditional Compilation chapter lists the available keys.
Restrictions#
| Restriction | Consequence |
|---|---|
| Extern functions have no contracts | The wrapper must validate the domain |
| Extern functions cannot be pure | The compiler cannot fold calls or use them in invariants |
| Extern functions cannot be first-class values | Store a Haze wrapper instead |
| Extern records cannot be generic | Use a concrete C layout |
| Extern records cannot have invariants | Validate at the wrapper boundary |
Extern fields must be scalar, ptr, or cstr |
Managed values cannot cross |
| Extern values cannot enter lists, records, or sums | Copy to a Haze representation first |
| No extern globals or extern blocks | Declare functions individually |
Ownership and Lifetime#
A C API may return a pointer whose ownership is transferred to the caller, borrowed for the duration of a call, or owned by the library. Haze does not encode any of these conventions. The wrapper must document the ownership and provide the matching release operation.
extern (C) strdup(text cstr) cstr = "strdup"
extern (C) free(pointer ptr) = "free"
fn duplicate(text str) Result[str, str] {
const copy = strdup(cstr::from_str(text))
if cstr::is_null(copy) {
return Error("allocation failed")
}
const result = cstr::to_str(copy)
free(ptr::from_cstr(copy))
return match result {
Success(value) => Success(value)
Error(_) => Error("invalid UTF-8")
}
}
The example frees the C allocation after converting it. The public function returns a Haze string and never exposes the C pointer. The conversion is performed before the free because cstr::to_str reads the C memory.
Wrapping a Foreign Call#
A good wrapper has a private extern declaration, a conversion layer, and a public Haze signature.
extern (C) getenv(name cstr) cstr = "getenv"
type EnvError =
| Missing(name str)
| Invalid(name str)
pub 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 is private. The public function takes a Haze str, returns a Haze Result, and names the failure cases. A caller does not need to know that the environment is stored as C strings.
Testing the Boundary#
Test the wrapper, not the C library. The wrapper's tests should cover a successful call, a null or missing result, an invalid encoding, and the ownership path when the wrapper frees memory. A test that calls the extern directly verifies the library, not the integration.
A wrapper that depends on a platform should be tested on each supported target. @cfg selects the declaration, but it cannot verify that the two implementations have the same behaviour.
Summary#
| Layer | Type | Responsibility |
|---|---|---|
| Extern declaration | cstr, ptr, scalars, extern records |
Match the C ABI exactly |
| Conversion | cstr::to_str, ptr::from_cstr, record copying |
Move between C and Haze representations |
| Public wrapper | Haze types, Result, contracts |
State the domain and guarantee |
The FFI Boundary chapter explains when a wrapper is justified and why most Haze code should never need one.