# FFI — Deep Dive

This page covers ABI, symbol export, callbacks, and ownership across a foreign
boundary. See the shorter [FFI guide](ffi.md) for basic imports.

## Scalar type mapping

Use fixed-width types whenever the foreign ABI permits it.

| Vex | C |
| --- | --- |
| `i8`, `u8` | `int8_t`, `uint8_t` |
| `i16`, `u16` | `int16_t`, `uint16_t` |
| `i32`, `u32` | `int32_t`, `uint32_t` |
| `i64`, `u64` | `int64_t`, `uint64_t` |
| `f32`, `f64` | `float`, `double` |
| `bool` | `_Bool` / `bool` when ABI-compatible |
| `char` | 32-bit Vex Unicode scalar; map explicitly, usually to `uint32_t` |
| `Ptr<Opaque>` | `void*` |
| `Ptr<T>`, `Ptr<T!>` | `const T*`, `T*` by capability contract |
| `()` return | `void` |

Pointer width depends on the target. Use `usize` only for C `size_t`-like
parameters and verify the target ABI.

## Importing foreign functions

Place these declarations in a `.vxc` boundary module. The fragments below show
individual ABI and ownership decisions; the [first native bridge](ffi-first-native.md)
provides a complete buildable project.

```vex
extern "LIBC" {
    fn malloc(size: usize): Ptr<Opaque!>
    fn free(memory: Ptr<Opaque>)
    fn memcpy(dst: Ptr<Opaque!>, src: Ptr<Opaque>, size: usize): Ptr<Opaque!>
}
```

Extern calls are unsafe by default:

```vex
let memory = unsafe { malloc(128) }
if !memory.isNull() {
    unsafe { free(memory) }
}
```

The provider belongs to the extern block. `LIBC` identifies the owner; it is
not a generic spelling for every function that happens to use the C calling
convention. Use `SYSTEM from "library"` for an OS library and `NATIVE from
"feature"` for a package-owned artifact.

## Exporting a C ABI symbol

The stable spelling for a defined, unmangled C ABI export is `export "C" fn`:

```vex
export "C" fn vexAdd(a: i32, b: i32): i32 {
    return a + b
}
```

```c
extern int32_t vexAdd(int32_t a, int32_t b);
```

This scalar example performs no pointer access. For a pointer-taking export,
a null/length check cannot prove that foreign memory is live, aligned or
accessible; state those caller obligations in the exported ABI contract.

Rust-style `#[no_mangle]` is not Vex syntax and is not needed. The export ABI
spelling controls the unmangled wrapper symbol.

## Aggregate layout

Do not assume that a normal Vex struct or enum automatically matches a C
aggregate. For a stable boundary:

1. prefer scalar parameters and opaque handles;
2. use fixed-width fields;
3. verify size, alignment, and offsets with compile-time assertions;
4. test the layout from both languages for every supported target.

The following checks deliberately describe one 64-bit layout expectation;
they should fail on an incompatible target rather than silently change the ABI.
Matching these two checks alone does not prove an entire foreign struct contract.

```vex
struct CHeader {
    version: u32,
    flags: u32,
    payload: Ptr<Opaque>,
}

#Diag.staticAssert(#Type.sizeOf<CHeader>() == 16, "CHeader size mismatch")
#Diag.staticAssert(#Type.offsetOf<CHeader>("payload") == 8, "payload offset mismatch")
```

Attribute spellings such as `#[repr(C)]` are not part of the stable Vex source
surface. If the verified native layout is insufficient, use explicit
serialization or an opaque C-owned object.

## Callbacks

A native Vex callable carries a code pointer and an environment/context
pointer in the current implementation. A C library may expect a single raw
function pointer with a different calling convention; writing `fn(...)` in a
declaration does not by itself establish that boundary. A top-level Vex
function has no local captures, but that alone does not prove C ABI
compatibility.

For a callback API, establish the exact foreign signature and use an adapter
whose generated entry point and call path have been verified for the target.
If the foreign API supplies a separate context pointer, its owner must keep it
valid until callbacks can no longer occur, and account for callback threads,
reentrancy and deregistration. A context pointer is necessary for carrying
state in such APIs but is not by itself proof that a Vex closure can be passed
directly. Never discard a captured environment by casting a callable to a raw
pointer. Keep the adapter's calling convention and context lifetime explicit
in the foreign API contract.

## Allocation ownership

Allocator identity must cross the boundary with the pointer contract.

```vex
extern "NATIVE" from "foreign_objects" {
    fn foreignCreate(): Ptr<Opaque>
    fn foreignDestroy(value: Ptr<Opaque>)
}

let foreign = unsafe { foreignCreate() }
if !foreign.isNull() {
    // Use the live foreign object before destroying it.
    unsafe { foreignDestroy(foreign) }
}

let size = 256 as usize
let vexMemory = Mem.alloc(size)
// Foreign code may borrow vexMemory, but Vex retains ownership.
unsafe { Mem.free(vexMemory, size) }
```

If ownership is transferred, export a matching destroy function instead of
asking the other language to guess the allocator:

```vex
// Foreign caller contract: the exact live pointer and allocation size returned
// by the matching Vex allocation API, passed once after all borrowers finish.
export "C" fn vexBufferDestroy(memory: Ptr<Opaque>, size: usize) {
    unsafe { Mem.free(memory, size) }
}
```

## Linking

Native libraries are selected by the feature named in `extern "NATIVE" from
"..."`. The owning `vex.json` maps that feature to target-specific `static`,
`dynamic`, or `bitcode` artifacts. Only features reached by codegen contribute
link arguments or runtime files.

On freestanding targets, activated `LIBC` uses are rejected before linking.
With `--no-runtime`, an activated `VEX` symbol must have a local VexArch
implementation; Vex reports `E0FFI36` instead of deferring the problem to an
undefined-symbol linker error.
If an activated static native artifact still leaves known libc/TLS symbols
undefined, Vex reports that exact active feature instead of silently producing
a hosted binary.

## Safety checklist

1. Match ABI, scalar width, pointer mutability, and variadic signatures exactly.
2. Treat every extern call and returned pointer as unsafe until validated.
3. Define nullability, ownership, allocator, lifetime, and thread rules.
4. Keep exported wrappers thin; convert to safe Vex types immediately inside.
5. Verify aggregate layout on every target, or use opaque handles.
6. Test both success and failure paths with sanitizers where available.

## Related

- [FFI](ffi.md)
- [Raw Pointers](types/raw-pointers.md)
- [Memory Prelude](memory/mem-prelude.md)
- [Freestanding](freestanding.md)
- [Native Module Linking](advanced/vxm-native-module-linking.md)
