Foreign Function Interface (v0.2.1)
Calling C functions through @extern and @convention attributes.
Overview
FFI declarations let Thrust call functions provided by C libraries or the system. The declaration writes the Thrust signature, the external symbol name, and the calling convention.
These declarations are low-level. A good pattern is to keep them in one module and expose small wrapper functions to the rest of the program.
The signature must match the external function. Pay close attention to pointer types, strings, integer widths, and variadic arguments.
Primary source: syntax/function/ffi.md
Syntax Signatures
fn printf(fmt: const array[char]) s32
@public
@arbitraryArgs
@extern("printf")
@convention("C");
fn atoi(text: const array[char]) s32
@public
@extern("atoi")
@convention("C");
Behavior and Use
@extern gives the linked symbol name.
@convention("C") uses the normal C calling convention.
Best Practices
- Keep raw extern declarations in dedicated modules.
- Prefer wrapper functions for code used by the rest of the program.
- Retest external bindings when upgrading C libraries.
External Symbols
FFI declarations describe symbols that are defined outside Thrust code.
- @extern("name") gives the exact linked symbol name.
- @convention("C") selects the C calling convention for calls across the boundary.
- @arbitraryArgs marks variadic functions such as printf-style declarations.
Safety Boundary
The compiler cannot verify that a C declaration matches the real C function.
- Match integer widths, pointer types, return type, and variadic arguments exactly.
- Keep raw declarations in one module and expose wrapper functions with clearer Thrust types.
- Retest bindings when the target platform, C library, or header declaration changes.
Example
fn atoi(text: const array[char]) s32
@public
@extern("atoi")
@convention("C");
fn parseInt(text: const array[char]) s32 @public {
return atoi(text);
}