Docs · Standard library

@c

@c exports c, the namespace that holds the C primitive types and every C declaration in the program, and two functions that convert strings between Vyi and C. This page lists what the package provides and the rules for each piece. Guide 15, C interop teaches the declaration forms, C pointers, and linking.

Vyi
import { c, cstrView, cstrDup } from "@c"

Exports

NameKindSummary
cnamespacethe C primitive types, and every c_fn, c_struct, c_enum, and c_union in the program
cstrViewfunctiona [*con]u8 view of a C string
cstrDupfunctiona C string copied from a [*con]u8

The c namespace

c contains:

  • the primitive types, always;
  • every c_fn, c_struct, c_enum, and c_union declared in any file the program loads, including packages such as @libc.

A C declaration is reached only through c: c_fn twice declares c.twice, and a bare twice is an undefined name. C names therefore never collide with Vyi names. There is one c for the whole program, whichever file or package made a declaration.

DeclarationGivesGuide 15
c_fn name(...) T { ... }a function with C's calling convention, written in Vyi; works on every targetdeclaring and calling
c_fn name(...) T (no body)a function from C code, found when the program linksfunctions from a C library
c_include "name"names the C library or module the bodyless c_fns come fromfunctions from a C library
c_struct Name { ... }a struct with C's layout; a field left out of a literal is zero, and fields have no defaultsc_struct
c_struct Name (no fields)an opaque type, used only behind a pointeropaque structs
c_struct(T)a c_struct with the fields of the Vyi struct Tderiving a c_struct
c_enum Name { ... }named c.int values, counting up from 0; = n sets onec_enum
c_enum(T)c.int, named after a payload-less Vyi enum Tc_enum
c_union Name { ... }C's union: every field at the same address, no tagc_union

c_union(T) is an error: a Vyi union's members have no names to give a C union's fields (`c_union(T) is not yet supported: a Vyi union's members are unnamed`).

A Vyi enum never converts to an integer, with or without payloads. The other way, the cast ?E(n) takes any integer, Vyi or C, and gives Some of the variant at position n of the payload-less enum E, counting from 0, or None for any other number (guide 15).

A call to c.name is checked like any call: the number of arguments, and each argument against its parameter's type. A c_fn parameter cannot be known (`parameter "n" cannot be known `). Optionals, tuples, arrays, and interfaces have no C layout, so a c_fn cannot take or return one by value. Rejecting a Vyi type such as i32 in a c_fn signature is (planned); write C types there.

What each target supports

x86-64-linux, arm64-linuxWebAssembly
c_fn with a bodyyesyes
bodyless c_fnmust name a function in the C standard library, which is always linked; other C files and libraries are (planned)from name.c beside the entry file (with c_include "name"), which vyi run compiles with clang; without that file, from a module the runtime provides, such as WASI
what crosses to a linked C libraryany C typescalars only (integers, floats, c.bool, a c_enum); a pointer, a C string, or a c_struct is an error (planned: linking C into the program's module)
a c_struct or c_union by valueas the platform's C compiler passes itas a pointer to the value
a c_fn passed to C as a callback(planned)(planned)

Guide 15 gives the calling convention in detail.

Primitive types

Each name is a type of its own. Most share a size and signedness with one Vyi type, their twin; the twin depends on the target:

C typeTwin on x86-64-linux, arm64-linuxTwin on WebAssembly
c.char, c.signed_chari8i8
c.unsigned_charu8u8
c.shorti16i16
c.unsigned_shortu16u16
c.inti32i32
c.unsigned_intu32u32
c.longi64i32
c.unsigned_longu64u32
c.long_longi64i64
c.unsigned_long_longu64u64
c.size_t, c.uintptr_tu64u32
c.ssize_t, c.intptr_ti64i32
c.floatf32f32
c.doublef64f64
c.long_doublef64f64
c.boolboolbool
c.voidnonenone
  • Twins convert where a type is written: a call argument, a return, a binding or assignment with a declared type, and a struct literal's field.
  • A change of size is never implicit. Convert with the type's name, as in c.size_t(count). A literal takes the type it is given, so c.reserve(64) needs no conversion.
  • A type name converts like a C cast. A float becomes an integer by dropping its fraction, toward zero: c.int(-3.9) is -3.
  • c.char is a byte. Vyi's char is a 32-bit code point; C string functions take c.char.
  • c.long_double is 64 bits in Vyi and wider in C on both Linux targets (80 bits on x86-64, 128 on arm64), so it does not match C's long double in a signature or a field.
  • c.void is for pointers only: *mut c.void is C's void *.
  • Code that passes an i64 for a c.long compiles on Linux and needs a conversion on WebAssembly.
Vyi · does not compile
import { c } from "@c"

fn main() !u8 {
    con total: c.long_long = 5
    con count: c.int = total   // error: this value has type c.long_long, but the binding is declared c.int
    return Ok(0)
}

Arithmetic on C integer types

A value of a C integer type follows C's rules in every build mode; a value of a Vyi type follows Vyi's. The conversion between them is the boundary.

Operation on a C integer typeRule
+, -, *, unary -wraps at the type's width (C leaves signed overflow undefined; Vyi wraps)
MIN / -1 (signed)wraps to MIN; MIN % -1 is 0
<<, >>the count is taken modulo the type's width
/ 0, % 0panics with division by zero, as on every integer type

A known computation on C integers wraps the same way instead of being a compile error. Once a value converts to a Vyi integer type, Vyi's rules apply, and a debug build panics on its overflow. Mixing a C type and its Vyi twin in one operator compiles today; rejecting it is (planned), so convert one side first.

Vyi
import { c } from "@c"
import { println } from "@fmt"

fn main() !u8 {
    con biggest: c.int = 2147483647
    println(biggest + 1)    // prints -2147483648
    con none: c.unsigned_int = 0
    println(none - 1)       // prints 4294967295
    con one: c.int = 1
    con shift: c.int = 33
    println(one << shift)   // prints 2
    con price: f64 = -3.9
    println(c.int(price))   // prints -3
    return Ok(0)
}

C pointers

*c_ptr T is C's pointer: it may be null, supports arithmetic (p + n) and indexing (p[i]) without bounds checks, and is always writable (guide 15, C pointers).

ConversionHowCheck
Vyi pointer to C pointerimplicit at a call, a return, or a typed binding: c.read(&value)none needed
array pointer to C pointerbuf.ptrnone needed
*mut T or [*mut]T to C pointercPtrOf(T, p) from @corenone needed
C pointer to Vyi pointer?*mut T(p) or ?*con T(p): None for null, else Somethe null test, in your code
optional pointer to C pointer*c_ptr T(o): None becomes nullnone
null*c_ptr T(None)none
between pointee types*mut c.void(p), *mut i32(v)none
C pointer to array pointertransmuteTo([*mut]T, p, count) from @memnone: you vouch for count

A C pointer never converts to a Vyi pointer without the ?*mut T(p) cast; assigning one is an error (this value has type *c_ptr c.int, but the binding is declared *mut c.int). The cast also states that the memory outlives the current function, so its result may be returned or stored; for memory C owns, that is your promise. A method whose receiver is a pointer cannot be called through a C pointer.

C strings

FunctionSignatureResult
cstrDupfn cstrDup(alloc: Allocator, s: [*con]u8) OutOfMemory!*mut c.chara copy of s with a zero byte after it, in s.len + 1 bytes from alloc; fails with OutOfMemory when alloc does
cstrViewfn cstrView(p: *mut c.char) [*con]u8a view of the bytes at p up to the first zero byte, which it leaves out; not a copy
  • cstrDup's result passes to a C parameter of type *c_ptr c.char directly. Free it through alloc.
  • cstrView takes a Vyi pointer, so it is never null: check a pointer from C with ?*mut c.char(p) first. The view is valid as long as C's memory is, and finding its length reads every byte up to the zero.
Vyi
import { cstrDup, cstrView } from "@c"
import { systemAllocator } from "@mem"
import { println } from "@fmt"

fn main() !u8 {
    con name = try cstrDup(systemAllocator, "Ada")
    con view = cstrView(name)
    println(view)       // prints Ada
    println(view.len)   // prints 3
    return Ok(0)
}

@libc

@libc declares the C standard library functions the standard library uses. It exports no names: import "@libc" adds these to c. WebAssembly has no libc, so on WebAssembly it declares nothing.

FunctionDeclaration
c.writec_fn write(fd: c.int, buf: *c_ptr c.unsigned_char, len: c.size_t) c.size_t
c.readc_fn read(fd: c.int, buf: *c_ptr c.unsigned_char, len: c.size_t) c.size_t
c.mallocc_fn malloc(size: c.size_t) *c_ptr c.unsigned_char
c.freec_fn free(p: *c_ptr c.unsigned_char)
c.mmapc_fn mmap(addr: *c_ptr c.unsigned_char, len: c.size_t, prot: c.int, flags: c.int, fd: c.int, off: c.long) *c_ptr c.unsigned_char
c.munmapc_fn munmap(addr: *c_ptr c.unsigned_char, len: c.size_t) c.int
c.memmovec_fn memmove(dst: *c_ptr c.unsigned_char, src: *c_ptr c.unsigned_char, n: c.size_t) *c_ptr c.unsigned_char
c.memcmpc_fn memcmp(a: *c_ptr c.unsigned_char, b: *c_ptr c.unsigned_char, n: c.size_t) c.int
c.memsetc_fn memset(p: *c_ptr c.unsigned_char, v: c.int, n: c.size_t) *c_ptr c.unsigned_char

c.malloc returns null on failure; check it with ?*mut c.unsigned_char(p). c.read and c.write return a c.size_t, so the C error result -1 arrives as the largest c.size_t. Code that uses @libc goes inside a file-level if on the target:

Vyi
import { c } from "@c"
import { targetOS } from "@target"

if targetOS != "wasm" {
    import "@libc"

    fn allocByte() ?*mut c.unsigned_char {
        return ?*mut c.unsigned_char(c.malloc(1))
    }
}

fn main() !u8 { return Ok(0) }

For memory and I/O on every target, use @mem and @io, which choose between libc and WASI for you.

See also: guide 15, C interop, the targets reference, and @core for cPtrOf.