Skip to content

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 bool pass as they are; &Str or Str arguments become NUL-terminated char* copies; a returned char* becomes a Str copy ("" for NULL) or Option<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_close is a C struct Brass only holds a pointer to. It is owned like any value: moved, never copied or cloned, and freed with the drop function when it goes out of scope. &Db passes the pointer; Db by value hands it to C; &mut Option<Db> is an out-parameter (Db**); returning Db panics on NULL, returning Option<Db> gives None.
  • 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.