Calling C
A foreign block declares C types and functions from a header; the
compiler includes the header and links the libraries named:
foreign "sqlite3.h" link "sqlite3" { type Db = sqlite3 drop sqlite3_close fn sqlite3_open(path: &Str, db: &mut Option<Db>) -> i32 fn sqlite3_errmsg(db: &Db) -> Str}- Signatures use Brass types, and each function gets a small generated C
wrapper that converts them: numbers and
boolpass as they are;&StrorStrarguments become NUL-terminatedchar*copies; a returnedchar*becomes aStrcopy (""for NULL) orOption<Str>;&Vec<u8>(or any number type) passes its data pointer. The C compiler checks every call against the real prototype in the header. type Db = sqlite3 drop sqlite3_closeis a C struct Brass only holds a pointer to. It is owned like any value: moved, never copied or cloned, and freed with thedropfunction when it goes out of scope.&Dbpasses the pointer;Dbby value hands it to C;&mut Option<Db>is an out-parameter (Db**); returningDbpanics on NULL, returningOption<Db>givesNone.- Foreign functions are private to the module that declares them, so the
unsafe surface is one module; the rest of the program uses the safe
Brass wrappers written next to them. Types may be
pub. - A header written
"./x.h"is found next to the Brass file.