Guides · 15
C interop
Vyi calls C through declarations you write in Vyi source. c_fn declares a
function, and c_struct, c_enum, and c_union declare types with C's
layout. There is no binding generator and no header parsing: you write the
declarations for the C you use.
Vyi's rules and C's rules stay on their own sides. A Vyi pointer is never null, a Vyi struct field always gets a value, and Vyi integer overflow is caught in a debug build. A C pointer may be null, a C struct field you leave out is zero, and C integer arithmetic wraps. A value's type says which side it is on, and a conversion between the two is always written in your code or happens at a call or an assignment, where the target type is written.
Declaring and calling a C function
Everything C lives under one name, c, which you import from @c. A c_fn
declares a function with C's calling convention, and you call it as
c.name. A c_fn with a body is written in Vyi:
import { c } from "@c"
import { println } from "@fmt"
c_fn add(a: c.int, b: c.int) c.int {
return a + b
}
fn main() !u8 {
println(c.add(2, 3)) // prints 5
return Ok(0)
}A c_fn with a body works on every target, with no C code involved. In a
Linux build it is emitted under its C name, add. Only a c_fn has a C
name; an ordinary fn never does.
Write a c_fn signature with C types, such as c.int, which the next section
lists. Rejecting a Vyi type such as i32 in a c_fn signature is
(planned).
A C name is reached only through c. Declaring c_fn twice gives you
c.twice, not twice:
import { c } from "@c"
import { println } from "@fmt"
c_fn twice(n: c.int) c.int {
return n * 2
}
fn main() !u8 {
println(twice(4)) // error: undefined name "twice"
return Ok(0)
}So C names never collide with yours. You can write your own fn write or
fn twice next to c.write or c.twice, and each name calls its own
function.
The c namespace is shared by the whole program: a c_fn declared in any
file the program loads is c.name in every file that imports c.
A call to c.name is checked like any other call: the argument count must
match, and each argument must fit its parameter's type.
C types
@c gives each C primitive type a name under c: c.int, c.size_t,
c.char, and so on. Each one is a type of its own, separate from Vyi's
types, but most share a size and signedness with one Vyi type: c.int and
i32 are both 32-bit signed integers. Such a pair are twins, and a value
converts between twins where the target type is written: a call argument, a
return, or a binding with a declared type.
import { c } from "@c"
import { println } from "@fmt"
c_fn square(n: c.int) c.int {
return n * n
}
fn main() !u8 {
con side: i32 = 4
con area: i32 = c.square(side)
println(area) // prints 16
return Ok(0)
}side is an i32 that becomes a c.int argument, and the c.int result
becomes the i32 binding area.
A conversion that changes the size is never implicit, as i32 doesn't
turn into i64 anywhere else in Vyi. c.size_t is 64-bit on Linux, so an
i32 needs a cast:
import { c } from "@c"
c_fn reserve(bytes: c.size_t) c.int {
return 0
}
fn main() !u8 {
con count: i32 = 64
c.reserve(count) // error: argument 1 has type i32
return Ok(0)
}Write c.reserve(c.size_t(count)). A literal takes the type it's given, so
c.reserve(64) needs no cast.
In arithmetic, give both operands the same type: convert one side first, as
in i32(count) + total. The compiler rejecting an operator that mixes a C
type with its Vyi twin is (planned).
The primitive types
On the Linux targets, x86-64-linux and arm64-linux, the twins are:
| C type | Vyi twin | C type | Vyi twin |
|---|---|---|---|
c.char, c.signed_char | i8 | c.unsigned_char | u8 |
c.short | i16 | c.unsigned_short | u16 |
c.int | i32 | c.unsigned_int | u32 |
c.long, c.long_long | i64 | c.unsigned_long, c.unsigned_long_long | u64 |
c.ssize_t, c.intptr_t | i64 | c.size_t, c.uintptr_t | u64 |
c.float | f32 | c.double, c.long_double | f64 |
c.bool | bool | c.void | none |
On WebAssembly, c.long, c.unsigned_long, c.size_t, c.ssize_t,
c.intptr_t, and c.uintptr_t are 32-bit, so their twins are i32 and
u32. c.long_long and c.unsigned_long_long are 64-bit everywhere. Code
that passes an i64 where C wants a c.long compiles on Linux and needs a
cast on WebAssembly.
c.char is a byte. Vyi's own char is a 32-bit Unicode character, so C
string functions take c.char, never char.
c.void is for pointers only, as in C's void *. c.long_double is a
64-bit float in Vyi, while C's long double is wider on both Linux targets,
so keep it out of declarations that must match C.
Conversions follow C
Each type name also converts a value, the way a C cast does. A float becomes a C integer by dropping its fraction:
import { c } from "@c"
import { println } from "@fmt"
fn main() !u8 {
con price: f64 = 19.99
println(c.int(price)) // prints 19
return Ok(0)
}Arithmetic on a C integer type wraps around, as it does in C, in every build
mode. The same overflow on an i32 panics in a debug build (guide
02):
import { c } from "@c"
import { println } from "@fmt"
fn main() !u8 {
con biggest: c.int = 2147483647
println(biggest + 1) // prints -2147483648
return Ok(0)
}Dividing by zero is still a panic. The
@c reference
lists every operator.
Functions from a C library
A c_fn without a body declares a function that lives in C code, and
c_include names the library it comes from:
import { c } from "@c"
import { println } from "@fmt"
c_include "libc"
c_fn abs(n: c.int) c.int
fn main() !u8 {
println(c.abs(-7)) // prints 7
return Ok(0)
}Checking the program never needs the C code: vyi check passes on a machine
with no C compiler. The C code is needed when the program is linked, and what
you can link depends on the target.
On Linux
vyi build and vyi run with --target x86-64-linux or
--target arm64-linux link through the system C compiler (cc, gcc, or
clang; for arm64-linux, aarch64-linux-gnu-gcc). The C standard library
is always linked, so any libc function works, as abs does above.
Linking your own .c files or other C libraries on Linux is (planned).
Today a c_fn without a body must name a function in the C standard library,
or the link fails with undefined reference.
Building a program that uses no C without any C toolchain is also (planned). Today every Linux build calls the system C compiler to link.
On WebAssembly
WebAssembly is the default target. When your entry file has
c_include "mylib" and a mylib.c sits in the same folder, vyi run
compiles mylib.c with clang and runs it next to your program:
// mylib.c, next to main.vyi
int add3(int a, int b) { return a + b + 3; }import { c } from "@c"
import { println } from "@fmt"
c_include "mylib"
c_fn add3(a: c.int, b: c.int) c.int
fn main() !u8 {
println(c.add3(1, 2)) // prints 6
return Ok(0)
}The C library runs as a separate WebAssembly module with its own memory, so
an address in your program means nothing to it. Only scalar values cross:
integers, floats, c.bool, a c_enum, or nothing. A pointer, a C string,
or a c_struct in the signature is an error on WebAssembly:
error: a linked C library has its own memory on wasm: `fill` takes
`*c_ptr c.int`, and only scalar values crossLinking the C code into your program's own module, so pointers can cross, is (planned).
A c_include with no matching .c file names a module the runtime provides,
such as WASI. vyi build for WebAssembly writes only your own module;
compiling the .c file is something vyi run does.
The C standard library: @libc
The standard package @libc declares the libc functions the standard
library itself uses: write, read, malloc, free, mmap, munmap,
memmove, memcmp, and memset. import "@libc" adds them to c.
WebAssembly has no libc, so @libc declares nothing there, and code that
uses it goes inside a file-level if on the target (guide
14):
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) }malloc returns a C pointer that may be null, and ?*mut T(...) turns it
into an optional, as the next section explains. For memory and I/O that work
on every target, use @mem and @io, which make this choice for you.
C pointers: *c_ptr T
A Vyi pointer is never null and supports only == and != (guide
09). C needs a looser kind, and that is
*c_ptr T:
- It may be null.
- It supports arithmetic and indexing, with no bounds checks.
- It is always writable.
A Vyi pointer becomes a C pointer at a call, so you pass &value straight
to a C pointer parameter. This is how C hands back extra results:
import { c } from "@c"
import { println } from "@fmt"
c_fn readSensor(out: *c_ptr c.int) c.int {
*out = 21
return 0
}
fn main() !u8 {
mut reading: c.int = 0
con status = c.readSensor(&reading)
if status == 0 {
println(reading) // prints 21
}
return Ok(0)
}Null pointers
A C pointer never turns back into a Vyi pointer by itself. The conversion is
the cast ?*mut T(p): it gives None for a null pointer and Some of a Vyi
pointer otherwise, so every null check is visible in your code. A null
pointer is written *c_ptr T(None):
import { c } from "@c"
import { println } from "@fmt"
fn show(p: *c_ptr c.int) {
if Some(value) = ?*mut c.int(p) {
println(*value)
} else {
println("null")
}
}
fn main() !u8 {
mut score: c.int = 7
show(&score) // prints 7
show(*c_ptr c.int(None)) // prints null
return Ok(0)
}*c_ptr T(o) goes the other way, from an optional pointer o to a C
pointer: None becomes null.
Assigning a C pointer to a Vyi pointer type is an error, because it would skip the check:
import { c } from "@c"
fn main() !u8 {
mut count: c.int = 1
con p: *c_ptr c.int = &count
con strict: *mut c.int = p // error: this value has type *c_ptr c.int, but the binding is declared *mut c.int
return Ok(0)
}The cast also tells the compiler that the memory behind the pointer outlives the current function, so the Vyi pointer it gives may be returned or stored. For memory C owns, that is a promise you make, as in C.
Arithmetic and indexing
p + n moves a C pointer n elements forward, and p[i] reads or writes
the element i places after p. cPtrOf(T, p) from @core makes a C
pointer from a Vyi pointer:
import { cPtrOf } from "@core"
import { println } from "@fmt"
fn main() !u8 {
mut prices = [4]i32[10, 20, 30, 40]
con p = cPtrOf(i32, &prices[0])
println(p[2]) // prints 30
println(*(p + 3)) // prints 40
return Ok(0)
}Nothing checks that p[i] stays inside the array. That is C's rule, and the
reason the type is separate.
To pass a buffer to C, use its .ptr: on a [*mut]u8, .ptr is a
*c_ptr u8. A C pointer made from a local must not outlive the function
that owns the local; the
memory model
has the rules.
Fields and methods
Field access reads and writes through a C pointer as it does through a Vyi
pointer: with p: *c_ptr Point, p.x is the field. A pattern over p
matches the value it points at, and p.sum() calls a method that takes its
receiver by value. Taking an address through a C pointer, as in &p.x, gives
another C pointer.
A method whose receiver is a pointer can't be called through a C pointer,
because that would make a Vyi pointer without the null check. Convert first
with ?*mut Point(p):
import { cPtrOf } from "@core"
struct Counter { count: i32 }
fn (counter: *mut Counter) bump() { counter.count += 1 }
fn main() !u8 {
mut clicks = Counter{ count: 0 }
con p = cPtrOf(Counter, &clicks)
p.bump() // error: cannot call "bump" here
return Ok(0)
}The compiler adds a note to that error: the method is defined for
*mut Counter, but not callable through a C pointer.
void *
C's void * is a pointer to c.void. A pointer cast changes the type a
pointer points at:
import { c } from "@c"
import { println } from "@fmt"
fn main() !u8 {
mut level = 42
con untyped = *mut c.void(&level)
con typed = *mut i32(untyped)
println(*typed) // prints 42
return Ok(0)
}C strings
A Vyi string is a [*con]u8 that knows its length. A C string is a pointer
to bytes ending in a zero byte. @c exports two functions that convert:
cstrDup(alloc, s)copiessinto memory fromalloc, adds the zero byte, and returns a*mut c.char. It fails withOutOfMemoryif the allocator does.cstrView(p)measures the C string atpand returns a[*con]u8over the same bytes, without the zero byte. It copies nothing, so the view is valid as long as C's memory is.
import { cstrDup, cstrView } from "@c"
import { systemAllocator } from "@mem"
import { println } from "@fmt"
fn main() !u8 {
con name = cstrDup(systemAllocator, "Ada") catch {
return Ok(1)
}
con view = cstrView(name)
println(view) // prints Ada
println(view.len) // prints 3
return Ok(0)
}The result of cstrDup passes straight to a C function that takes a
*c_ptr c.char. On Linux, this calls libc's puts:
import { c, cstrDup } from "@c"
import { systemAllocator } from "@mem"
c_include "libc"
c_fn puts(text: *c_ptr c.char) c.int
fn main() !u8 {
con text = cstrDup(systemAllocator, "hi from C") catch {
return Ok(1)
}
c.puts(text) // prints hi from C
return Ok(0)
}cstrView needs a pointer that isn't null. When C may return null, check
first with ?*mut c.char(p).
c_struct
A c_struct is a struct with C's layout: fields in the order you write
them, with C's alignment and padding. That is what makes it safe to pass to
C. In Vyi code it works like any struct:
import { c } from "@c"
import { println } from "@fmt"
c_struct Size {
width: c.int,
height: c.int,
}
c_fn area(s: c.Size) c.int {
return s.width * s.height
}
fn main() !u8 {
con box: c.Size = _{ width: 3, height: 4 }
println(c.area(box)) // prints 12
return Ok(0)
}The struct is c.Size, under c like every C name, so its literal uses the
inferred form _{ ... } with the type on the binding.
A field you leave out of a c_struct literal is zero, as C code expects:
import { c } from "@c"
import { println } from "@fmt"
c_struct Size { width: c.int, height: c.int }
fn main() !u8 {
con box: c.Size = _{ width: 3 }
println(box.height) // prints 0
return Ok(0)
}The same literal for a Vyi struct is an error, because every Vyi field needs a value:
struct Size { width: i32, height: i32 }
fn main() !u8 {
con box = Size{ width: 3 } // error: missing field
return Ok(0)
}For the same reason, a c_struct field can't declare a default value:
import { c } from "@c"
c_struct Size {
width: c.int = 1, // error: cannot declare a default
height: c.int,
}
fn main() !u8 { return Ok(0) }Optionals, tuples, arrays, and interfaces have no C layout, so a c_fn
can't take or return one. Pass a pointer, or put the data in a c_struct:
import { c } from "@c"
c_fn find(id: ?c.int) c.int // error: by-value non-C
fn main() !u8 { return Ok(0) }Converting a struct to a c_struct
A Vyi struct converts to a c_struct with the same field names, and back,
by the rule that converts between any two structs with matching fields
(guide 03). Each pair of fields must be twins.
The conversion happens at a call, a return, or a typed binding, and
c.Size(box) writes it out:
import { c } from "@c"
import { println } from "@fmt"
c_struct Size { width: c.int, height: c.int }
struct Box { width: i32, height: i32 }
c_fn area(s: c.Size) c.int {
return s.width * s.height
}
fn main() !u8 {
con box = Box{ width: 3, height: 4 }
println(c.area(box)) // prints 12
return Ok(0)
}A pair of fields that aren't twins, such as an i32 and a c.long_long,
blocks the conversion. Convert those fields one at a time.
Deriving a c_struct: c_struct(T)
Instead of writing a c_struct that repeats a Vyi struct, derive one.
c_struct(Box) is a c_struct with Box's fields, in the same order:
import { c } from "@c"
import { println } from "@fmt"
struct Box { width: i32, height: i32 }
type CBox = c_struct(Box)
c_fn area(b: CBox) c.int {
return b.width * b.height
}
fn main() !u8 {
con box = Box{ width: 3, height: 4 }
println(c.area(box)) // prints 12
return Ok(0)
}Every field must have a C form: a primitive, a pointer, another struct
(derived in turn), or a c_union. A field that doesn't, such as an enum with
payloads, is an error that names the field:
import { c } from "@c"
enum Shape { Circle(i32), Dot }
struct Drawing { shape: Shape, layer: i32 }
type CDrawing = c_struct(Drawing) // error: field shape
fn main() !u8 { return Ok(0) }Opaque structs
A c_struct with only a name, and no fields, is opaque: C knows what's
inside and Vyi doesn't. It has no size, so you only ever hold a pointer to
it. C's FILE is one:
import { c } from "@c"
import { println } from "@fmt"
c_include "libc"
c_struct FILE
c_fn tmpfile() *c_ptr c.FILE
c_fn fclose(file: *c_ptr c.FILE) c.int
fn main() !u8 {
con file = c.tmpfile()
println(c.fclose(file)) // prints 0
return Ok(0)
}Anything that needs the size is an error: a binding, field, or element of the type itself, or arithmetic and indexing on a pointer to it.
c_enum
A c_enum is a C enumeration: named c.int values. They count up from 0,
and = n sets a value that later names count on from:
import { c } from "@c"
import { println } from "@fmt"
c_enum Status {
Idle,
Busy,
Failed = 10,
Retrying,
}
fn main() !u8 {
con code: c.int = c.Status.Retrying
println(code) // prints 11
return Ok(0)
}A c_enum is an integer and nothing more: it has no payloads, and nothing
checks that a value is one of its names.
A Vyi enum is not an integer, so it doesn't convert to one, even when it has no payloads:
import { c } from "@c"
enum Shade { Light, Dark }
fn main() !u8 {
con n = c.int(Shade.Dark) // error: cannot cast Shade
return Ok(0)
}c_enum(T) names c.int after a payload-less Vyi enum T, as in
type CShade = c_enum(Shade), for signatures where you want the
correspondence visible. It is c.int and converts like c.int.
From a C integer to a Vyi enum
When C hands you an integer that stands for a Vyi enum, the cast
?Weekday(n) picks the variant at position n, counting from 0. Any other
number, including a negative one, gives None:
import { c } from "@c"
import { println } from "@fmt"
enum Weekday { Mon, Tue, Wed }
fn dayName(code: c.int) [*con]u8 {
return match ?Weekday(code) {
Some(Mon): "Monday",
Some(Tue): "Tuesday",
Some(Wed): "Wednesday",
None: "unknown",
}
}
fn main() !u8 {
println(dayName(1)) // prints Tuesday
println(dayName(9)) // prints unknown
return Ok(0)
}The cast works from any integer type, Vyi or C, and only to an enum without
payloads. An integer never turns into an ?Enum without it.
c_union
A c_union is C's union: every field starts at the same address, so writing
one field and reading another reads the same bytes as a different type. There
is no tag and no check:
import { c } from "@c"
import { println } from "@fmt"
c_union Bits {
asUnsigned: c.unsigned_int,
asSigned: c.int,
}
fn main() !u8 {
con bits: c.Bits = _{ asUnsigned: 4294967295 }
println(bits.asSigned) // prints -1
return Ok(0)
}All 32 bits set is the largest c.unsigned_int, and -1 as a c.int. You
keep track of which field holds the meaningful value, as in C.
How values are passed, in detail
You need this section only if you write the C side yourself or debug a
mismatch. Arguments and results follow the platform's C calling convention,
the same one whichever side is calling. A by-value c_struct or c_union
travels exactly as the platform's C compiler passes it.
x86-64-linux (System V). Integer and pointer arguments use rdi, rsi,
rdx, rcx, r8, and r9, in order. f32 and f64 use xmm0 to
xmm7, counted separately. Further arguments go on the stack in 8-byte
slots. An integer or pointer result comes back in rax, a float in xmm0.
A struct of up to 16 bytes is split into two 8-byte halves. A half holding
only c.float or c.double fields goes in a float register, any other half
in an integer register. If the registers it needs have run out, the whole
struct goes on the stack, and later arguments still use the registers that
are left. A larger struct is copied onto the stack. A result too large for
registers is written to memory the caller provides, whose address is passed
in rdi.
arm64-linux (AAPCS64). Integer and pointer arguments use x0 to x7,
floats use v0 to v7. A struct of one to four fields of the same float
type goes in float registers. Any other struct of up to 16 bytes goes in
integer registers as its raw bytes. If too few registers of the kind it
needs remain, it goes on the stack, and so do later arguments of that kind.
A larger struct is copied and passed by address. A result too large for
registers is written to memory the caller provides, whose address is passed
in x8.
WebAssembly. A by-value struct is passed as a pointer to the value. This
applies to a c_fn with a body and to a module the runtime provides. Passing
a struct that holds one scalar as that scalar, as the WebAssembly C
convention does, is (planned), together with linking C into your module.
c.long_double is a 64-bit float in Vyi but wider in C on both Linux
targets (80-bit on x86-64, 128-bit on arm64), so it doesn't match C's
long double in a signature or a field.
Passing a c_fn to C as a callback, through a C function pointer, is
(planned).
See also: the @c reference, the
targets reference, and guide
09, Pointers and memory.