docs

你正在阅读 v0.1.0 的文档。Nabi 0.1.0 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#1.7. FFI - extern "C" / CStr / CString / CPtr

本页内容

The bare::ffi module provides the mechanism for defining external functions and data compatible with the C ABI. It works together with the extern "C" { ... } block defined by refs-lang 5.9 extern block.

Besides CStr / CString the module holds C's types (types, also in the prelude, 1.7.9), Handle for Nabi values C holds (1.7.10), the saved errno (1.7.11), wchar_t strings (1.7.12) and Library for loading shared libraries (1.7.13).

This chapter covers only traditional C FFI; FFI based on the WASM Component Model is described separately in 1.8 wit.

#1.7.1. extern "C" block

The most basic form is:

nabi
extern "C" {
    // function declarations
    fn malloc(size: usize) -> CPtr<u8>;
    fn free(ptr: CPtr<u8>);
    fn strlen(s: ConstPtr<c_char>) -> usize;

    // global (read-only)
    static environ: CPtr<CPtr<c_char>>;

    // global (mutable): the `mut` keyword is allowed _only here_
    static mut atexit_count: u64;
}

C's errno is not a global variable but a per-thread macro, so it cannot be declared as a static; #[errno] saves it after a call (1.7.11). C's integer types are written with their C names (c_int, c_long, c_size_t, 1.7.9), which have the right size on every target.

The mut keyword appearing here is defined in refs-lang 1.5 keywords and has meaning only in this position. It cannot be used on ordinary variables.

##[link("name")] - specifying a library

To specify a library explicitly, use the #[link] attribute.

nabi
#[link("c")]
extern "C" {
    fn malloc(size: usize) -> CPtr<u8>;
    fn free(ptr: CPtr<u8>);
}

#[link("m")]
extern "C" {
    fn cos(x: f64) -> f64;
    fn sin(x: f64) -> f64;
}

The linker attaches flags such as -lc or -lm automatically.

#Calling convention

Two calling conventions can be named for C code; "nabi" is the runtime ABI (refs-lang 5.9.2). Any other ABI string is an error (E0025).

nabi
extern "C" { ... }              // System V (Unix) / Microsoft x64 (Windows)
extern "system" { ... }         // Windows: stdcall on x86, C on x64 / aarch64

The default "C" is enough for most users. "system" appears mainly when dealing with the Windows API.

##[leaf] - short calls

nabi
#[leaf]
extern "C" {
    fn abs(x: c_int) -> c_int;
    fn labs(x: c_long) -> c_long;
}

Every extern "C" call parks the calling thread: while C runs, the thread counts as stopped for the collector, so a collection may run during the call (1.7.7, refs-lang 8.4.10). #[leaf] on a block or on one declaration leaves that bracket out, which makes a short call cheaper. A leaf function must return soon, must not block (a lock, I/O, a sleep) and must not call back into Nabi: while it runs, the thread holds back every collection in the process, so a leaf that blocks stalls every thread that allocates. A debug toolchain checks that the thread never stops for a collection inside a leaf call. #[leaf] on an extern "nabi" block is an error (1.7.11).

#str parameters and returns

A str parameter of an extern "C" function is passed as a NUL-terminated char* (refs-lang 5.9.4). A str result is an error, since C owns the bytes of a returned char*: declare it ConstPtr<c_char> | none and copy it with CStr::from_ptr (1.7.2). (ptr, len) passing belongs to the runtime ABI extern "nabi" (5.9.2).

nabi
extern "C" {
    fn puts(s: str) -> i32;          // "hi" → NUL-terminated char*
    fn getenv(name: str) -> CPtr<c_char>;   // may be null; received as CPtr
}

#C compilers and the platform ABI

The C ABI of each target is the platform's ABI document: the System V psABIs (x86-64, i386), AAPCS64, AAPCS32 with VFP, the RISC-V psABI, ELFv2, the s390x ELF ABI, the WebAssembly C ABI, and Microsoft's x64 / x86 / ARM64 conventions. The toolchain's tests check every target against the C compilers that build its libraries, from a generated table of signatures (structs, unions, homogeneous float aggregates, f16 / bf16, Simd, over-aligned and packed structs, register exhaustion, variadic tails, results of every size, both directions): gcc 15.2 and clang 21 on Linux (x86-64, i686, aarch64; clang for armv7, riscv64, powerpc64le and s390x, whose cross gcc the test machines lack), Apple clang 21 on macOS, MSVC 14.44 (cl, the reference) and clang-cl 22 on Windows x64 and i686, MSVC 14.44 and clang on Windows ARM64.

Where the compilers disagree, the document wins:

  • AArch64 __bf16 inside an aggregate: AAPCS64 counts it as a half-precision float, so a struct of __bf16 is a homogeneous float aggregate in v registers, as clang passes it. gcc 15.2 passes such a struct in integer registers; declare the C side with uint16_t fields when the C library is built by gcc.
  • f16 / bf16 on i686: gcc passes _Float16 only with SSE2 (-msse2, the baseline nabi's i686 targets assume), as clang does.
  • MSVC lays out a packed struct holding an over-aligned member with that member's alignment; nabi does the same on *-windows-msvc targets, and the GNU layout elsewhere.

Not covered: long double wider than 8 bytes, __int128 and _Complex (no nabi form), C++ empty structs (C has none).

#1.7.2. CStr / CString - null-terminated string

CStr is the borrowed type for handling C strings.

from_ptr copies the C string in, up to its NUL, so the result is always a valid C string. It is an unsafe fn: a dangling pointer, or one to bytes without a NUL, is undefined behavior. Every constructor copies, so checking the bytes costs nothing extra and there is no unchecked form; from_bytes_until_nul reads a fixed-size C buffer whose tail after the NUL is garbage. CStr / CString keep bytes and NUL in one GC object; as_ptr is valid as str::as_ptr is (2.15.2): while a variable holding the CStr / CString is in scope in a function where a pointer value can appear.

#CString - owned, null-terminated

When an owned form is needed, use CString.

nabi
struct CString { /* GC heap, null-terminated */ }

impl CString {
    fn new<B: AsBytes>(bytes: B) throws (NulError) -> CString;
                                        // rejects interior null bytes; a str gives its UTF-8

    fn as_c_str(self) -> CStr;
    fn as_ptr(self) -> ConstPtr<c_char>;
    fn into_bytes(self) -> List<u8>;     // owned bytes (excluding null)
    fn into_bytes_with_nul(self) -> List<u8>;
}

The error types say where the bytes went wrong; each implements Display (its message()), Debug, Error, PartialEq, Eq and Clone, and NulError's fields are private (0.5.10).

nabi
struct NulError { .. }
impl NulError {
    fn position(self) -> usize;     // index of the interior NUL (CString::new)
    fn message(self) -> str;        // "nul byte found at position 1"
}

enum FromBytesWithNulError {       // CStr::from_bytes_with_nul
    InteriorNul { position: usize; },   // a NUL before the last byte
    NotNulTerminated,                   // the last byte is not a NUL
}
impl FromBytesWithNulError {
    fn message(self) -> str;        // "interior nul byte at 3"
}

struct FromBytesUntilNulError;    // no NUL at all (CStr::from_bytes_until_nul); message()

#Example - strlen

nabi
extern "C" {
    fn strlen(s: ConstPtr<c_char>) -> usize;
}

let s: str = "hello";
let cs = try CString::new(s);
let n = unsafe { strlen(cs.as_ptr()) };       //→ 5

Note

Conversion between str and CStr requires an allocation (a null terminator must be added). str is generally not null-terminated, so converting explicitly only at FFI sites is recommended.

#1.7.3. CPtr<T> and nullability

The authoritative definition is in 1.1.5 CPtr. When a C function returns T*, the possibility of null must be made explicit, and this is the type used there.

nabi
extern "C" {
    fn fopen(path: ConstPtr<c_char>, mode: ConstPtr<c_char>) -> CPtr<FILE>;
    fn fclose(file: CPtr<FILE>) -> i32;
}

struct FILE;        // opaque

let path = try CString::new("data.txt");
let mode = try CString::new("r");
let f: CPtr<FILE> = unsafe { fopen(path.as_ptr(), mode.as_ptr()) };

match f.as_ptr() {
    file: Ptr<FILE> => {
        // use
        unsafe { fclose(f) };
    }
    none => panic("fopen failed"),
}

#1.7.4. using block - RAII

The GC runs no finalizers, so an external resource is released by Drop, which the compiler calls at a fixed point: where the value's owner leaves scope, on every exit, or at the end of a using block that binds it (2.13.4). bare::ffi has no file API of its own: the wrapper below declares the C functions itself and closes the handle in Drop.

The using syntax itself is governed by refs-lang 3.17 using expression and works integrated with the Drop trait of 2.13 marker.

#1.7.5. Safe wrapper pattern - separating sys and safe

The standard idiom in the Rust ecosystem is to separate a *-sys crate (raw FFI) from a same-named crate (safe wrapper). Nabi recommends the same pattern.

This separation confines unsafe code to a narrow area. User code then calls only the safe wrapper, which secures safety.

#1.7.6. Automatic binding generation

nabi bindgen (refs-lang 9.10.8) generates Nabi declarations from a C header. It reads the header with the front end of the toolchain's C compiler nabicc (refs-lang 9.13), which preprocesses, parses and lays out C as the target's C compiler does; no other C compiler and no libclang is needed.

bash
nabi bindgen libfoo.h > libfoo_sys.nabi
nabi bindgen libfoo.h --target=x86_64-pc-windows-msvc -o libfoo_sys.nabi -- -I include -DFOO=1

The output is for one target (--target, default the host): sizes, layouts and integer widths are those of its C ABI. The arguments after -- are C compiler options (refs-lang 9.10.8). The machine's system headers are used for its own platform, for Apple targets (the SDK) and for MSVC targets on an MSVC host (INCLUDE, else the newest Visual Studio and Windows SDK); for any other target only the compiler's built-in headers (stddef.h, stdint.h, stdarg.h, stdbool.h, limits.h, float.h, ...) are, unless --sysroot is given after --, and the target's headers are passed after -- (-isystem <dir>). The declarations of the header and of the non-system headers it includes are written out (for a header in a system directory, also those of the headers it includes from its own directory tree), together with the declarations of other headers that they use. A header the front end rejects is an error (exit 1) at its file:line:col.

The mapping conventions are:

  • C integer and floating-point types become the Nabi primitive of their size on the target (int → i32, long → i32 or i64, char → c_char, _Bool → bool, _Float16 → f16, __bf16 → bf16); size_t / uintptr_t → usize, ssize_t / intptr_t / ptrdiff_t → isize. A system header's typedef of such a type is that type.
  • typedefs become Nabi type aliases.
  • structs and unions map to #[repr(C)] struct / union (#[repr(C, align(N))] or #[repr(packed)] where the target's layout needs it). A run of bitfields becomes one byte-array field _bitfieldN covering its storage. A layout Nabi cannot express (#pragma pack(N) with N > 1, a bitfield in a union) becomes a struct of the same size and alignment holding _opaque: [u8; N]. A struct declared but not defined becomes struct Name; (opaque).
  • enums become an alias of their integer type and one const per enumerator (pub type color = u32; pub const RED: color = 0;); an unnamed enum is its constants.
  • object pointers (T*, const T*) become CPtr<T>; void* becomes CPtr<u8>.
  • array parameters are pointers, as C adjusts them (char buf[16] → CPtr<c_char>), and a function-typed parameter is a function pointer.
  • functions become extern "C" fn (a C variadic, and a function declared without a prototype (f()): ...); stdcall functions on 32-bit x86 Windows go into extern "system". Globals become static (static mut unless const). Static and inline functions are skipped (no symbol to link).
  • function pointers become unsafe extern "C" fn(...) -> R | none (refs-lang 5.9.4; NULL = none).
  • object-like macros that evaluate to an integer, floating-point or string constant become const items.
  • a C name that is a Nabi keyword or primitive type name gets a trailing _; functions and statics keep their C symbol with #[link_name].
  • anything else (128-bit integers, __fp16, long double wider than 8 bytes, vector and block types, variadic function pointers, thread-local variables, other calling conventions) is skipped with a // skipped ... comment. A struct written as bytes (_opaque) is never passed by value: a function or function pointer that takes or returns one, directly or inside another struct, is skipped, since C classifies it by its fields.

#The C bindgen reads

The front end reads C17 with the extensions system headers use, as clang does for the target:

  • the preprocessor: the target's predefined macros (__x86_64__, _WIN32, __APPLE__, __SIZEOF_LONG__, _MSC_VER on MSVC targets and __GNUC__ on the others, ...), #include, #include_next, __has_include, #if arithmetic with defined, __has_attribute, __has_builtin and __has_feature, object- and function-like macros with #, ##, __VA_ARGS__ and __VA_OPT__, _Pragma / __pragma, and #pragma pack, once, push_macro / pop_macro; other pragmas are ignored.
  • declarations with __attribute__((..)), __declspec(..), [[..]], __asm__("symbol") labels, nullability qualifiers, __extension__, typeof, _Alignas, _Atomic, _Static_assert, anonymous structs and unions, bitfields, flexible array members, enums with a fixed type, block pointers (^) and vector types. Function bodies and initializers are skipped (nabicc reads and compiles them, refs-lang 9.13).
  • the built-in headers that stand for clang's own (stddef.h, stdint.h, stdarg.h, stdbool.h, limits.h, float.h, ...), among them the intrinsic headers: on x86 immintrin.h, x86intrin.h and the mmintrin.h .. nmmintrin.h, wmmintrin.h family (MMX through SSE4.2, AVX, AVX2, FMA, F16C, BMI, BMI2, LZCNT, POPCNT, AES, PCLMUL and CRC32 as prototypes; the AVX-512 and AMX types without their functions), on Arm arm_neon.h, arm_acle.h, arm_fp16.h and arm_bf16.h, and on MSVC targets intrin.h (with x86intrin.h on x86). Each intrinsic is a declaration without a body, never bound; the vector types (__m128, __m256i, float32x4_t, ..) are skipped as above, and a struct holding one becomes bytes. On another architecture such a header is an error, as with clang (#include <immintrin.h> on Arm).
  • record layout by the target's rules: System V or Microsoft bitfields, #pragma pack, packed, aligned, __declspec(align), mode.
  • constant expressions (array sizes, enum values, bit widths, alignments, _Static_assert, macro values) of integer, floating, character and string literals, enum constants, casts, sizeof, _Alignof, offsetof (__builtin_offsetof, or &((T *)0)->m) and the arithmetic, bitwise, comparison, logical and conditional operators.

The dialect is GNU C17 whatever -std= says. What it does not read is an error at its file:line:col that says what to write instead:

ConstructWrite instead
a K&R-style function definition (int f(a, b) int a; ..)a prototype: int f(int a, int b)
an implicit int (static x;)the type: static int x;
an array size, enum value, bit width or alignment it cannot evaluate (another __builtin_ call, _Generic, a statement expression)an integer constant expression of the forms above
an unknown type nameits declaration, or the #include of the header that declares it, before the use
a header that is not found-I <dir> / -isystem <dir> after --; for a target that is not this machine's platform, its headers (-isystem <dir> or --sysroot <dir>)

#1.7.7. Division of call-safety responsibility

Who is responsible for what at the call site:

ItemResponsible party
Pointer null checkNabi code, for C → Nabi
Buffer length validationNabi code (must know the length)
String null-terminationAutomatic on CString creation
GC pinNabi code, for every pointer into a GC object it passes to C (1.6.5)
Nabi values C keepsNabi code, through Handle (1.7.10)
Freeing memory (free)Nabi code or safe wrapper
Matching calling conventionThe extern declarer
C type sizesThe extern declarer, with the c_* names (1.7.9)
Thread safetyPer the C library's documentation
Errno / GetLastError#[errno] on the declaration (1.7.11)
A panic in a function C calledThe runtime aborts, or returns the #[on_panic] value (refs-lang 5.9.12)

Every extern "C" call parks the thread (1.7.1), so a collection may run during any C call, however short. A pointer into a GC object (a list's buffer, a StrBuf's bytes) is valid during the call only while the object is pinned; a str argument is the one exception, since its root keeps it in place (1.6.5). The compiler leaves no pin out on its own.

#1.7.8. Comparison with other languages

Widening the comparison makes Nabi's position clearer.

AspectCRustZigGoNabi
External functions(direct)extern "C" { ... }extern "..."import "C" (cgo)extern "C" { ... }
Calling convention(one default)extern "system" etc.extern "C" etc."C" only"C" / "system"
C stringchar*CStr / CString[*:0]u8C.CString / C.GoStringCStr / CString
nullable ptr(default)Option<*const T>?*T*C.struct_T (always nullable)CPtr<T>
binding toolnonebindgen / cbindgen@cImportcgonabi bindgen
C sources(the compiler)an external C compiler (cc crate)zig cc (built in)an external C compiler (cgo)nabi cc / c in the manifest (built in)
C types(native)core::ffi::c_int etc.c_int etc.C.int etc.c_int etc. (prelude)
GC pinN/AN/AN/Aruntime.Pinner (1.21+)bare::gc::pin
Values C holds(direct)Box::into_raw(direct)runtime/cgo.Handlebare::ffi::Handle
Run-time loadingdlopen(crates)std.DynLib(none)bare::ffi::Library
RAII / using(manual)Dropdeferdeferusing block (Drop)

Nabi's biggest differences come down to three points.

  1. Integration of the GC and FFI. Using the Pinned<T> guard together with using blocks prevents both resource leaks and missed pins.
  2. A strict pointer model. Ptr<T> / ConstPtr<T> / ManyPtr<T> / CPtr<T> are separate (1.1).
  3. Enforced safe wrappers. as casts are rejected and only named casts are allowed (1.2).

#1.7.9. C types - c_int, c_long, c_void

bare::ffi::types names C's integer and floating-point types as the target's C compiler sizes them. The prelude has every one, so a declaration needs no use.

NameC typeNabi type
c_schar / c_ucharsigned char / unsigned chari8 / u8
c_short / c_ushortshort / unsigned shorti16 / u16
c_int / c_uintint / unsigned inti32 / u32
c_long / c_ulonglong / unsigned longi32 / u32 on Windows and on 32-bit targets; i64 / u64 elsewhere
c_longlong / c_ulonglonglong long / unsigned long longi64 / u64
c_size_t / c_ssize_tsize_t / ssize_tusize / isize
c_ptrdiff_tptrdiff_tisize
c_intptr_t / c_uintptr_tintptr_t / uintptr_tisize / usize
c_wcharwchar_tu16 on Windows; u32 on Linux for arm and aarch64; i32 elsewhere
c_float / c_doublefloat / doublef32 / f64
c_voidvoid, behind a pointeran empty struct

c_char is a language type of its own (2.15.5).

Each name is a type alias (pub type c_int = i32;), chosen per target with #[cfg]: on one target c_int and i32 are the same type, and values pass between them without a conversion. The fixed-size type is right only where it matches C's: fn labs(x: i64) -> i64 is correct on 64-bit Linux and macOS, and wrong on Windows, where long has 32 bits. Written with c_long, the declaration holds on every target.

c_void is an empty struct that stands for C's void behind a pointer: CPtr<c_void> is a void*, ConstPtr<c_void> a const void*. No c_void value is made or read.

nabi
extern "C" {
    fn labs(x: c_long) -> c_long;
    fn strlen(s: str) -> c_size_t;
}

let x: c_long = -3;
println(f"{unsafe { labs(x) }} {unsafe { strlen("abc") }}");    //→ 3 3
let p: CPtr<c_void> = CPtr::null();                             // a null void*

#1.7.10. Handle<T> - Nabi values C holds

A C API that calls back takes a void* user_data and passes it to the callback. Handle<T> carries a Nabi value through that pointer.

nabi
// bare::ffi
#[repr(transparent)]
struct Handle<T> { /* a handle number, pointer-sized */ }

impl<T> Copy for Handle<T> {}

impl<T> Handle<T> {
    fn new(value: T) -> Handle<T>;                     // keeps value alive and in place until the last release
    unsafe fn from_ptr(p: CPtr<c_void>) -> Handle<T>;  // the handle C passed back
    fn as_ptr(self) -> CPtr<c_void>;                   // the void* to pass to C
    fn get(self) -> T;                                 // the value
    fn set(self, value: T);                            // replaces the value every copy of the handle sees
    fn retain(self);                                   // one more release before the value is let go
    fn release(self);                                  // lets the value go after as many releases as new and retains
}

Handle::new puts the value in a GC cell that the handle roots and pins: the value stays alive and keeps its address until the last release, however many collections run while C holds the pointer. get returns the same object for a List, a Dict or another shared value, so a callback that pushes to a list changes the caller's list; a plain value (an integer, a struct) is copied out. retain is for C code that keeps a second copy of the pointer: each retain needs one more release.

The pointer is a handle number, never null and never an address: C must not read through it. Handle<T> is Copy, pointer-sized and #[repr(transparent)] over CPtr<c_void>, so it can be a field of a #[repr(C)] struct. It implements Clone and Debug.

from_ptr is unsafe: p must come from Handle::<T>::new(..).as_ptr(). get, set, retain and release check the handle and panic when it is wrong:

  • after its last release (or a value that is no handle): handle already released (or not a handle): call `release` once per `Handle::new` and `retain`, and not `get` after the last one
  • with another type than it was made with: this handle holds `List<str>`, not `Dict<str, i64>`: write `Handle::<List<str>>::from_ptr(p)`

A closure is a value like any other. Its own type cannot be written, so it is stored as a fn type: Handle::<fn(c_int)>::new(|x: c_int| ..). A handle made with Handle::new(closure) and read as Handle::<fn(i32)> panics with this handle holds a closure, not `fn(i32) -> ()`: make it with `Handle::<fn(i32) -> ()>::new(..)` and read it with `Handle::<fn(i32) -> ()>::from_ptr(p)` .

A C callback is an extern "C" fn, which captures nothing (refs-lang 5.9.10). To call a closure from C, keep it in a handle and pass a one-line extern "C" fn that reads it back and calls it; there is no generic trampoline. A closure passed to a C function directly is an error whose help says to do this.

The runtime side is nabi_handle_new / nabi_handle_get / nabi_handle_retain / nabi_handle_release (refs-lang 8.5.12).

#1.7.11. #[errno] - errno and GetLastError

nabi
#[errno]
extern "C" {
    fn open(path: str, flags: c_int, ...) -> c_int;
}

extern "C" {
    #[errno]
    fn chdir(path: str) -> c_int;
}

// bare::ffi
fn errno() -> c_int;            // errno as the last #[errno] call on this thread left it
fn set_errno(v: c_int);         // the saved value and the C library's errno
fn last_error() -> u32;         // Windows: GetLastError as that call left it; 0 elsewhere
fn set_last_error(v: u32);      // the saved value and, on Windows, SetLastError

Between a C call's return and the next line the thread may run runtime code: it may wait out a collection when it leaves the native state, and it unpins the copy of a str argument. That code may change errno. #[errno] on an extern "C" or extern "system" block, or on one declaration in it, makes the call save errno (and on Windows GetLastError) in per-thread slots right after it returns, before anything else runs. errno() and last_error() read the saved values, so they are the call's whenever they run.

Without the attribute nothing is saved: errno() returns what the last #[errno] call (or set_errno) on the thread left. set_errno sets both the saved value and the C library's errno, for C functions that report errors only through it (strtol: set 0, call, read). io::IoError::last_os_error() (2.23.0) makes an IoError from the saved values: on Windows the saved GetLastError when it is nonzero, else the saved errno.

nabi
use bare::ffi::{errno, set_errno};

let fd = unsafe { open("/no-such-dir/file", 0) };     //→ -1
let e = io::IoError::last_os_error();                 // e.kind() == NotFound, e.os_code() == 2
set_errno(0);

#[errno] on any other item is an error: on a function, `#[errno]` cannot be attached to a function; it goes on an extern block or an extern function; on an extern "nabi" block (the runtime keeps errno itself), `#[errno]` and `#[leaf]` are for C declarations: put them on an `extern "C" { .. }` block or its functions.

#1.7.12. WideCStr / WideCString - wchar_t strings

The Windows W APIs and C's wchar_t functions take NUL-terminated strings of c_wchar units. These types hold such a string: UTF-16 on Windows, one unit per char (UTF-32) elsewhere. The API is the same on every target.

Both keep their units and the NUL in one GC object and implement Clone, PartialEq, Eq, Hash and Debug (WideCString("hi")). as_ptr is valid as CStr::as_ptr is (1.7.2). from_ptr copies the C string in, as CStr::from_ptr does: p must be null or point at a live NUL-terminated wchar_t string. WideCString::new throws NulError (1.7.2) at a NUL in the str. WideCStr::to_str throws str::Utf16Error (2.15.6) at an unpaired surrogate on Windows, and elsewhere at a unit that is no char; valid_up_to() is the unit index.

UTF-16 itself, without the NUL or a pointer, is str::encode_utf16, str::from_utf16 and str::from_utf16_lossy (2.15.6). A buffer C fills is a pinned List<u16>, read back with str::from_utf16:

nabi
// Windows
use bare::ffi::WideCString;
use bare::gc::pin;
use bare::ptr::{ConstPtr, Ptr};

extern "system" {
    fn SetEnvironmentVariableW(name: ConstPtr<u16>, value: ConstPtr<u16>) -> i32;
    fn GetEnvironmentVariableW(name: ConstPtr<u16>, buf: Ptr<u16>, size: u32) -> u32;
}

let name = try WideCString::new("NABI_WIDE_TEST");
let value = try WideCString::new("h\u{E9}\u{1F600}");
unsafe { SetEnvironmentVariableW(name.as_ptr(), value.as_ptr()) };

let buf: List<u16> = [];
for _ in 0..1024 { buf.push(0u16); }
let held = pin(buf);
let n = unsafe { GetEnvironmentVariableW(name.as_ptr(), held.as_data_ptr(), 1024u32) };
let back = try str::from_utf16(buf[0:n as usize]);     //→ "hé😀"

#1.7.13. Library - loading shared libraries

open loads a shared library at run time: dlopen(path, RTLD_NOW | RTLD_LOCAL) on Unix, LoadLibraryW on Windows. A bare name searches the system's library path. this() is the program itself: on Unix its own symbols and those of every library it was linked with, on Windows only what the executable exports. raw_symbol gives a symbol's address. symbol::<F> gives a function as F, which must be a C function pointer type (extern "C" fn(f64) -> f64, extern "system" fn() -> u32); another type panics before the address is turned into it: `symbol::<i32>`: write the C function pointer type, `extern "C" fn(..) -> R`. It is unsafe because F must be the symbol's real signature.

A library is never unloaded implicitly: Library has no Drop, and close is the only way. close is unsafe because every pointer taken from the library (a symbol, data it returned) dangles afterwards; closing this() does nothing. Library implements Clone and Debug (Library("kernel32.dll"), Library(this)).

The messages are the system's (dlerror, FormatMessageW). LoadError displays as cannot load {path}: {message} (cannot close .. from close), SymbolError as cannot find symbol {name}: {message}; a NUL in the path or name is an error before the system is asked (the path has a NUL byte at 1; remove it). Both implement Display, Debug, Error, PartialEq, Eq and Clone. A target without dynamic loading (wasm32, no OS) has the type, and open throws with this target has no dynamic loading.

nabi
use bare::ffi::Library;

fn main() throws (bare::ffi::LoadError | bare::ffi::SymbolError) {
    let lib = try Library::open("libm.so.6");
    let cos = try unsafe { lib.symbol::<extern "C" fn(f64) -> f64>("cos") };
    println(f"{unsafe { cos(0.0) }}");                      //→ 1
    try unsafe { lib.close() };
}

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