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
- Each field sits where C would put it: at the next offset that is a multiple of its size.
ps + 1is the address of the secondPoint, and*secondreads it, as in C.- A record read back through a
Ptris checked against itsinvariants, like a new one. - A record never goes to C by value: always through a pointer.