Skip to content
Kavachकवच

Calling C: Records

● Advanced3 min

A record of C types is laid out as a C struct, and reaches C through a Ptr: Ptr<Point> is C's struct point*.

type Point {
    x: Int32
    y: Int32
}

fn main() {
    unsafe {
        const ps: Ptr<Point> = alloc(2)
        ps.write(0, Point(x: 1, y: 2))
        ps.write(1, Point(x: 3, y: 4))
        print(ps.read(1).y)
        const second = ps + 1
        print((*second).x)
        free(ps)
    }
}

The program ran and printed:

kavach run

43
src/main.kav: Kavach code, then what running it prints
  • Each field sits where C would put it: at the next offset that is a multiple of its size.
  • ps + 1 is the address of the second Point, and *second reads it, as in C.
  • A record read back through a Ptr is checked against its invariants, like a new one.
  • A record never goes to C by value: always through a pointer.