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.
Extern Functions#
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, contract, generic parameter, or the pure modifier, and cannot be used as a value.
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#
type DivResult extern {
quot i32
rem i32
}
extern (C) div(num i32, den i32) DivResult = "div"
Extern records cannot declare type parameters or invariants. Fields must be scalar, ptr, or cstr. Managed types such as List, records, sums, and Option are rejected. Extern values cannot appear 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.
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.
C Strings#
cstr is a nullable pointer to a null-terminated byte sequence.
| 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. Comparing cstr values with == compares addresses; convert to str for content equality.
Raw Pointers#
| 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. A pointer carries no length or lifetime; the wrapper is responsible for both.
Calling and Linking#
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. -cc selects the compiler and -target selects the ABI.
Platform Variation#
@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. See Conditional Compilation.
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 that is owned by the caller, borrowed for a call, or owned by the library. Haze does not encode these conventions. The wrapper must document 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 conversion is performed before the free because cstr::to_str reads the C memory.
Wrapping a Foreign Call#
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.
Testing the Boundary#
Test the wrapper, not the C library. Cover a successful call, a null or missing result, an invalid encoding, and the ownership path when the wrapper frees memory. A wrapper that depends on a platform should be tested on each supported target.
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 |
See The FFI Boundary.