docs

#Calling a C library

On this page

Declare libc's strlen, getpid, getenv, snprintf and qsort in an extern "C" block, and manage C memory directly with the pointer and allocation functions of bare.

#Code

#Walkthrough

  • An extern "C" { ... } block holds only signatures without bodies. Functions declared there are implicitly unsafe, so every call goes inside unsafe { ... } (5.9 extern blocks, 4.15 unsafe).
  • A str parameter is passed to C as a NUL-terminated char*. That is why strlen("naïve") returns 6, the UTF-8 byte count, not the 5 characters (5.9.4 FFI-compatible types).
  • A C pointer that may be NULL is received as a CPtr. as_const() gives a non-null ConstPtr or none, so a single ? wraps getenv into a safe function returning str | none (Sum types).
  • Memory is allocated by hand with Layout and alloc / dealloc, and accessed like a C array through ManyPtr's read(i) / write(i, v). The GC does not manage it, so you free it yourself.
  • extern "C" fn descending is a Nabi function compiled with the C ABI. Passed to qsort as a function pointer, it lets C call back into Nabi code while sorting (5.9.10 defining extern fn).
  • Variadic functions such as snprintf are declared with ... at the end of the signature. See the FFI chapter for more.

Found a mistake? Edit this page on GitHub. Last updated