LEVIATHAN vd52e79c4 · d52e79c486

Standard Library

namespace ffi

Calling C libraries, and describing C data, from Leviathan.

since 0.1.0-alpha.1linuxwindowswasm

Overview

A foreign function is declared with an empty body and the @extern attribute naming its library; a call then crosses to C with each argument converted to its C type. Structs marked @repr("C") get C's field layout so they can be passed by value or packed into a Block; ffi::callback turns a Leviathan function into a C function pointer. A program that declares foreign functions must be built with the --native flag, or by trident from a package that lists its native libraries.

See the reference entries on foreign functions, C-layout structs and callbacks for the full rules: which types cross the boundary and how, struct layout, callbacks, errors, variadic functions, and threads.

Examples

Calling the C library

uses ffi;
use io::console;

@extern("c")
int strlen(string s);

@extern("c", "abs")
int32 cAbs(int32 n);

@extern("m")
float cos(float x);

void main() {
    console.writeln(strlen("hello"));
    console.writeln(cAbs(-7));
    console.writeln(cos(0.0));
}
main();
5
7
1.0e0

Types

  • Callback — A Leviathan function made callable from C, returned by ffi::callback.
  • export — Exports a Leviathan function to C under a C symbol.
  • extern — Declares a foreign (C) function.
  • FfiException — The error raised by the foreign-function machinery.
  • inline — Makes a Block field of a @repr("C") struct a fixed array of bytes stored inside the struct.
  • Library — A dynamically loaded library, for looking up raw addresses in it.
  • mayCallback — Asserts that a foreign function may call back into Leviathan through a callback registered earlier.
  • reentrant — Asserts that a foreign function tolerates another task entering its library while a callback from that library is waiting.
  • repr — Gives a value struct C's field layout.
  • shallow — Asserts that a foreign function uses little stack, so it runs on the task's own stack with no stack switch and no headroom check.

Functions

alignOf

alignOf<S>() -> int

The alignment in bytes of a @repr("C") struct in C layout.

Returns

The largest alignment of its fields.

Examples

The alignment of a struct

uses ffi;
use io::console;
use ffi;

@repr("C")
struct Wide {
    byte tag;
    int value;
}

comptime int align = ffi::alignOf::<Wide>();
console.writeln(align);
8

alloc

alloc(int bytes) -> Ptr

Allocates foreign memory with the C allocator.

A size of 0 is allowed and returns a valid, non-null address of its own (one byte is allocated), which must still be released.

Parameters

bytes
The size.

Returns

The address of the memory; release it with ffi::free.

Throws

ffi.FfiException
when bytes is negative.

Examples

Allocating foreign memory

uses ffi;
use ffi;
use io::console;

void main() {
    Ptr p = ffi::alloc(8);
    ffi::view(p, 8).setInt64(0, 1234);
    console.writeln(ffi::view(p, 8).int64At(0));
    ffi::free(p);
}
main();
1234

available

available(string lib) -> bool

Whether an optional native library was found when the program was built.

Parameters

lib
The library nickname.

Returns

true when its functions can be called.

Examples

The always-available libraries

uses ffi;
use ffi;
use io::console;

console.writeln(ffi::available("c"));
console.writeln(ffi::available("m"));
true
true

callback

callback<F>(F f) -> Callback

Makes a Leviathan function callable from C.

The function's parameter and result types, which must be known where callback is called, select the C signature; each must cross the C boundary. A throw inside the callback returns zero to C and is raised again after the foreign call returns.

Parameters

f
The function.

Returns

The handle holding the C function pointer; close it when C no longer needs it.

Throws

ffi.FfiException
when every slot of that signature is in use.

Examples

Sorting with a Leviathan comparator

uses ffi;
use ffi;
use io::console;

@extern("c")
void qsort(Block base, int nmemb, int size, (Ptr, Ptr) => int32 compar);

void main() {
    Block data = Block(12);
    data.setInt32(0, 3);
    data.setInt32(4, 1);
    data.setInt32(8, 2);
    Callback cmp = ffi::callback::<(Ptr, Ptr) => int32>((Ptr a, Ptr b) => {
        int x = ffi::view(a, 4).int32At(0);
        int y = ffi::view(b, 4).int32At(0);
        return x < y ? 1 : (x > y ? -1 : 0);
    });
    qsort(data, 3, 4, cmp);
    console.writeln(data.int32At(0));
    console.writeln(data.int32At(8));
    cmp.close();
}
main();
3
1

cstring

cstring(string s) -> Block

A copy of a string with a terminating zero byte, for C code that keeps the pointer.

A string argument is only borrowed for the length of a call. When C stores the pointer, pass this block (or its ptr()) instead and keep the block alive as long as C uses it.

Parameters

s
The text.

Returns

A block of s.length() + 1 bytes ending in 0.

Examples

A zero-terminated copy

uses ffi;
use ffi;
use io::console;

Block b = ffi::cstring("hi");
console.writeln(b.length());
console.writeln(b.byteAt(2));
3
0

errno

errno() -> int

The C errno captured right after the last foreign call declared with errno = true on this thread.

Returns

The error number.

Examples

Reading errno after a failed call

uses ffi;
use ffi;
use io::console;

@extern("c", "chdir", errno: true)
int32 cChdir(string path);

cChdir("/no/such/directory");
console.writeln(ffi::errno());
2

free

free(Ptr p) -> void

Releases memory obtained from ffi::alloc.

Parameters

p
The address alloc returned.

Examples

Releasing foreign memory

uses ffi;
use ffi;
use io::console;

void main() {
    Ptr p = ffi::alloc(4);
    ffi::view(p, 4).setInt32(0, 99);
    console.writeln(ffi::view(p, 4).int32At(0));
    ffi::free(p);
}
main();
99

lastError

lastError() -> int

The Windows GetLastError() value captured after the last foreign call declared with errno = true on this thread; 0 on other systems.

Returns

The error code.

Examples

The Windows error code

uses ffi;
use ffi;
use io::console;

@extern("c", "chdir", errno: true)
int32 cChdir(string path);

cChdir("/no/such/directory");
console.writeln(ffi::lastError());
0

nullPtr

nullPtr() -> Ptr

The null address.

Returns

A Ptr whose address is 0.

Examples

The null address

uses ffi;
use ffi;
use io::console;

Ptr none = ffi::nullPtr();
console.writeln(none.isNull());
console.writeln(none == ffi::nullPtr());
true
true

offsetOf

offsetOf<S>(string field) -> int

The byte offset of a field of a @repr("C") struct in C layout.

Parameters

field
The field's name.

Returns

Its offset from the start of the struct.

Examples

The offset of a field

uses ffi;
use io::console;
use ffi;

@repr("C")
struct Wide {
    byte tag;
    int value;
}

comptime int at = ffi::offsetOf::<Wide>("value");
console.writeln(at);
8

pack

pack<S>(S s) -> Block

Packs a @repr("C") struct into a new block in C layout.

Parameters

s
The struct.

Returns

A block of ffi::sizeOf bytes.

Examples

Packing a struct

uses ffi;
use ffi;
use io::console;

@repr("C")
struct Pt {
    int32 x;
    int32 y;
}

Block b = ffi::pack(Pt(7, 9));
console.writeln(b.length());
console.writeln(b.int32At(4));
8
9

provide

linuxwindows

provide(string lib, string path) -> void

Names the file a dynamically loaded library comes from, before its first use.

Parameters

lib
The library nickname.
path
The library file.

Examples

Naming a plugin file

uses ffi;
use io::console;

@extern("plugin", "plugin_version")
int32 pluginVersion();

void main() {
    ffi::provide("plugin", "/opt/example/libplugin.so");
    console.writeln(pluginVersion());
}
main();
not run — the library is a dynamic [[native]] table of a build plan and a plugin file of the program's own, neither of which a docs example has

ptr

ptr(int addr) -> Ptr

A pointer from an integer address.

Parameters

addr
The address.

Returns

A Ptr holding it.

Examples

A pointer from a number

uses ffi;
use ffi;
use io::console;

Ptr p = ffi::ptr(4096);
console.writeln(p.addr());
console.writeln(p == ffi::ptr(4096));
4096
true

sizeOf

sizeOf<S>() -> int

The size in bytes of a @repr("C") struct in C layout.

The value depends on the target: pointers take 4 bytes on wasm32 and 8 elsewhere.

Returns

The size, including trailing padding.

Examples

uses ffi;
use io::console;
use ffi;
@repr("C") struct Header { int32 tag; int length; }
comptime int size = ffi::sizeOf::<Header>();
console.writeln(size);
16

strerror

strerror(int e) -> string

The C library's description of an error number.

Parameters

e
The error number, usually ffi::errno().

Returns

The message.

Examples

Describing an error number

uses ffi;
use ffi;
use io::console;

console.writeln(ffi::strerror(2));
No such file or directory

toString

toString(Ptr p) -> string

The text of a zero-terminated C string.

Parameters

p
The start of the string.

Returns

A copy of the bytes before the first zero byte.

Throws

ffi.FfiException
when p is null.

Examples

Reading a C string

uses ffi;
use ffi;
use io::console;

Block b = ffi::cstring("hello");
console.writeln(ffi::toString(b.ptr()));
console.writeln(ffi::toString(b.ptr(), 2));
hello
he
toString(Ptr p, int len) -> string

The text of len bytes of foreign memory.

Parameters

p
The start of the bytes.
len
The number of bytes.

Returns

A copy of the bytes.

Throws

ffi.FfiException
when p is null or len is negative.

unpack

unpack<S>(Block b) -> S

Reads a @repr("C") struct from the start of a block in C layout.

Parameters

b
The bytes.

Returns

The struct.

Examples

Unpacking from an offset

uses ffi;
use ffi;
use io::console;

@repr("C")
struct Pt {
    int32 x;
    int32 y;
}

void main() {
    Block b = Block(16);
    b.setInt32(8, 5);
    b.setInt32(12, 6);
    Pt p = ffi::unpack::<Pt>(b, 8);
    console.writeln(p.x + p.y);
}
main();
11
unpack<S>(Block b, int off) -> S

Reads a @repr("C") struct from a block in C layout, starting at a byte offset.

Parameters

b
The bytes.
off
The byte offset of the struct in b.

Returns

The struct.

view

view(Ptr p, int len) -> Block

A Block over len bytes of foreign memory starting at p.

The block reads and writes that memory directly, with the usual bounds checks against len. It does not own the memory: the runtime never frees it, and using the block after the memory is gone is the program's error, as in C.

Parameters

p
The start of the memory.
len
The number of bytes.

Returns

A block over the memory.

Throws

ffi.FfiException
when p is null.

Examples

A view over a block's own bytes

uses ffi;
use ffi;
use io::console;

void main() {
    Block b = Block(8);
    b.setInt32(0, 41);
    Block v = ffi::view(b.ptr(), 8);
    v.setInt32(0, v.int32At(0) + 1);
    console.writeln(b.int32At(0));
}
main();
42

See also

  • Ptr — An opaque address of foreign (C) memory or code.