External functions
mach's foreign function interface (FFI) is a single declaration form: ext fun. It declares a body-less function with the C ABI - a forward reference the linker resolves at link time. Declare the foreign symbol, call it like any other function, and supply its definition (a C object, archive, or shared library) when you build. Apart from an #[intrinsic] function, this is the only body-less function form mach allows. ext val and ext var are the data counterparts, importing a binding whose storage lives in another object.
Grammar
An ext fun is a function signature with no body. The declaration ends with a semicolon instead of a block.
ext fun NAME(args) RET;
- No body block - the declaration ends with a semicolon.
- Argument and return types must be representable in C.
- No type parameters and no
$comptime parameters, since each instance would be a function no foreign library exports. pub ext funexposes the import to other modules; withoutpubit is file-private.
pub ext fun libc_write(fd: i64, buf: *u8, n: i64) i64;
ext fun strlen(s: *u8) i64; # private, file-local
The C ABI boundary
The C ABI is the contract at the boundary: every argument and return type must be representable in C, and values are passed exactly as the target's C calling convention dictates. mach's fixed-width scalars and pointers correspond directly to their C counterparts.
i8throughi64andu8throughu64are the sized C integers, andu128andi128are__int128.f16,f32andf64are C_Float16,floatanddouble.*Tand**Tare C pointers; a C-style string is a*u8.
The exact calling convention is the one declared for the target (for example sysv64 on Linux or win64 on Windows). See Manifest for how a target's abi is set.
C-variadic imports
A C function declared int open(const char *, int, ...) is C-variadic, and it is spelled the same way: a bare trailing ... after the last fixed parameter. At least one fixed parameter must precede it. The form exists only on an ext fun, since a mach function's variadic is the comptime pack va: ... (see Variadic packs), and mach cannot define a C-variadic function. The same shape is a function type, so a C-variadic function can be stored and called through a value.
ext fun open(path: *u8, flags: i32, ...) i32;
ext fun printf(fmt: *u8, ...) i32;
def Printf: fun(*u8, ...) i32;
A tail argument has no declared type, so it is held to C's default argument promotions directly. mach inserts no implicit conversion, so an integer narrower than 32 bits or an f32 is refused, naming the cast:
printf("%c\n", c); # error: `u8` is promoted to a 32-bit integer in a C-variadic argument. write the cast `x::i32` or `x::u32`
printf("%c %.1f\n", c::i32, f::f64); # correct
A secret may not enter a variadic tail. A va_list a C callback receives is declared with #[abi_type("va_list")] on a bodyless def, whose layout the selected target supplies. It can be received as a parameter and passed on to the C function that consumes it, and nothing else.
#[abi_type("va_list")]
pub def VaList;
ext fun vprintf(fmt: *u8, args: VaList) i32;
Renaming the linker symbol
The declaration names a C declaration, so its linker symbol is what the target's C toolchain emits for that identifier: the name as written on Linux and Windows, and with an underscore prefixed on Darwin. The prefix is never spelled in source. The #[symbol("real_name")] decorator overrides it, binding the declaration to a different external symbol. The target's C prefix is applied to an overridden name too.
#[symbol("write")]
pub ext fun libc_write(fd: i64, buf: *u8, n: i64) i64;
Two common reasons to rename:
- The C name (such as
write) would shadow other things in your namespace. - The target decorates symbol names in its ABI and you need to match the decorated form.
Library attribution
On a two-level dynamic format, PE (Windows) or Mach-O (Darwin), the #[library("...")] decorator pins an ext import to the dependency that exports it. The value names a link dependency by its identity: the table key of a [link.X] entry, or the name given to -l. A loader name such as ws2_32.dll does not bind.
#[library("ws2_32")]
ext fun WSAStartup(ver: u16, data: *u8) i32;
- The named library must be among the link's dependencies. Pinning to an absent one is a link error,
import 'WSAStartup' pinned to library 'ws2_32' not among the link's dependencies, never a silent fallback. - An import with no
libraryis unattributed, and PE and Mach-O require every dynamic import to name its provider, so an unattributed import is a link error there. A symbol a linked static archive leaves undefined, with noextdeclaration to decorate, is attributed by thesymbolskey of the[link.X]entry that supplies it. - On ELF (Linux) the loader resolves imports by global search, so
libraryhas no effect on the emitted binary; the value is still validated against the dependency set.
library composes with symbol: the rename sets the imported symbol's name, library sets the DLL it is imported from.
# imported as `socket` from the ws2_32 entry, called as `ws2_socket` in mach.
#[library("ws2_32")]
#[symbol("socket")]
ext fun ws2_socket(af: i32, kind: i32, proto: i32) i64;
Linking the definition
An ext fun is only a forward reference. Its definition is supplied at link time, either statically by a precompiled object or archive or dynamically by a shared library bound at load time. Provide those inputs to mach build on the command line or through the manifest. An undefined ext symbol that no input resolves is a link error when code the link keeps refers to it, so a typo never silently drops a dependency. An ext fun called only from code nothing reaches needs no definition.
mach build . path/to/libfoo.a # static archive (only the members it needs)
mach build . -L build/libs -l foo # search dir + name, found as a shared library
mach build . -l c # link libc dynamically
A -l name is a shared library and nothing else. It is searched for only where the target's environment provides system libraries, which on Linux is env = "gnu" in the target. A target that states no env refuses it:
error[link.input_invalid] the target states no environment that provides system libraries, so `c` has nowhere to be found (linux)
In the manifest, an artifact names typed [link.X] requirements in its link array, and each entry's sys, arch and abi filters select the build cells it applies to:
[link.c]
source = "system"
name = "c"
sys = ["linux"]
arch = ["*"]
abi = ["*"]
[artifact.app]
link = ["c"]
A loose .o object or static .a archive is a static input merged into the binary, and an archive contributes only the members that define a symbol still undefined. A shared .so, .dylib, framework or .dll is a dynamic dependency whose undefined ext functions become run-time imports. A static definition always wins over a same-named dynamic import.
The link-input resolution rules - explicit paths, -l/-L search order, and static-vs-dynamic selection - are documented once on the CLI page, and the manifest overlay on the Manifest page.
A worked example
This program imports two libc functions, calls them, and prints a line to standard output. strlen measures the message and libc_write (the renamed write) writes it to file descriptor 1.
use std.runtime;
#[symbol("write")]
pub ext fun libc_write(fd: i64, buf: *u8, n: i64) i64;
ext fun strlen(s: *u8) i64;
#[symbol("main")]
fun main(argc: i64, argv: **u8) i64 {
val msg: *u8 = "hello from ffi\n";
val n: i64 = strlen(msg);
libc_write(1, msg, n);
ret 0;
}
libc supplies both symbols, so link it dynamically, from a target that states env = "gnu". The result is a dynamically-linked binary that binds write and strlen at load time.
$ mach build . -l c
built example linux-x86_64 debug
./out/linux-x86_64/debug/bin/example 40 KiB 27 modules 274ms
$ ./out/linux-x86_64/debug/bin/example
hello from ffi
See also
- Visibility -
pubandextmodifiers - Decorators - the
symbolandlibrarydirectives - CLI - external link inputs and resolution
- Manifest -
[link.X]requirements - Variadic packs - the comptime pack, the variadic form a mach function takes
- Functions - regular function declarations