Foreign Function Interface (v0.2.1)

Calling C functions through @extern and @convention attributes.

Latest

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

External Symbols

FFI declarations describe symbols that are defined outside Thrust code.

Safety Boundary

The compiler cannot verify that a C declaration matches the real C function.

Example

fn atoi(text: const array[char]) s32
    @public
    @extern("atoi")
    @convention("C");

fn parseInt(text: const array[char]) s32 @public {
    return atoi(text);
}

Back to language reference