Declarations
C-layout structs (@repr C)
Give a value struct C's field layout so it can cross to C by value or be packed into bytes; ffi::sizeOf, alignOf and offsetOf read the layout.
since 0.1.0-alpha.1linuxwindowswasm
Description
@repr("C") on a value struct declares that, wherever the struct meets C, it has the layout a C
compiler would give the same fields. Everywhere else it stays an ordinary Leviathan struct: copied by
value, compared field by field, stored the usual way in arrays. The attribute checks that every field
has a C type, records the layout, and lets the struct be passed to and returned from foreign functions
by value.
Layouts fold at compile time
uses ffi;
use io::console;
use ffi;
@repr("C")
struct Point {
int32 x;
int32 y;
}
@repr("C")
struct Rec {
Point at;
float32 w;
Ptr next;
}
comptime int recSize = ffi::sizeOf::<Rec>();
comptime int recAlign = ffi::alignOf::<Rec>();
comptime int nextAt = ffi::offsetOf::<Rec>("next");
console.writeln("Rec: " + recSize.toString() + " bytes, aligned to " + recAlign.toString());
console.writeln("next is at byte " + nextAt.toString());
Rec: 24 bytes, aligned to 8
next is at byte 16
The layout is C's: fields in declaration order, each at the next offset that is a multiple of its own
alignment, the struct aligned to its most-aligned field, and its size rounded up to that alignment. A
nested @repr("C") struct is laid out inline. Pointers (Ptr, string, and Block addresses) are 8
bytes, or 4 on the WebAssembly target, so the same struct can have a different size there: built with
--target wasm32-unknown-unknown, Rec above is 16 bytes and next sits at byte 12.
A fixed-size byte array inside the struct is a Block field marked @inline(n): it occupies n bytes
at alignment 1. C unions and bitfields have no Leviathan form; describe a union as an @inline(size)
byte array and read it through a Block.
Passing a struct by pointer
Many C functions take a pointer to a struct they fill in. ffi::pack(s) returns a new Block holding
the struct in C layout; pass the block (or block.ptr()) and read the result back with
ffi::unpack::<S>(block), optionally from a byte offset. An array of structs for C is one block of
n * ffi::sizeOf::<S>() bytes, filled with pack and blit and read back with
ffi::unpack::<S>(buf, i * ffi::sizeOf::<S>()). Both directions copy; there is no view of a Leviathan
array as C memory.
A struct filled in by C
uses ffi;
use ffi;
use io::console;
@repr("C")
struct Pt {
int32 x;
int32 y;
}
@extern("pt", "scale")
void scale(Block p, int32 k);
@extern("pt", "add")
Pt add(Pt a, Pt b);
void main() {
Block buf = ffi::pack(Pt(2, 3));
scale(buf, 10);
Pt scaled = ffi::unpack::<Pt>(buf);
Pt sum = add(scaled, Pt(1, 1));
console.writeln(sum.x);
}
Rules
@repr("C")applies to a valuestructonly (@repr("C") requires a value struct ('S')); the layout name must be"C". The struct may not be generic or declare accessors, and needs at least one field (@repr("C") struct 'S' has no fields).- Each field must have a C type: the scalar rows of
lang.ffi's table,Ptr,Ptr?,string,string?, another@repr("C")struct, or an@inline(n)Block. Anything else is@repr("C") field 'f' of 'S' has non-marshalable type 'T'. A plainBlockfield is not allowed. @inline(n)applies to aBlockfield of a@repr("C")struct (@inline requires a Block field inside a @repr("C") struct), andnmust be positive. When packed, the firstnbytes of the block are copied and any remainder is filled with zeros; when unpacked, the field is a new block of exactlynbytes. Astringfield is unpacked as a copy of the C string; aNULLpointer in astringfield throwsRuntimeException(C struct field 'S.name' is NULL for a string), and in astring?field it unpacks asNone. Declare the fieldstring?when C may leave itNULL.ffi::sizeOf::<S>(),ffi::alignOf::<S>()andffi::offsetOf::<S>("field")need a@repr("C")struct (ffi::sizeOf: 'S' is not a @repr("C") struct) and, foroffsetOf, the field's name as a string literal (ffi::offsetOf: unknown field 'f'). They are constants: acomptimeinitializer folds them.ffi::pack(s)returns a new block offfi::sizeOfbytes. Astringfield is packed as a BORROWED pointer to zero-terminated bytes, valid only while its source lives: for a string of eight bytes or more the source is the string itself; on the native backends a string of up to seven bytes is copied into storage that belongs to the packed block, so its pointer lives as long as that block. A copy of the block's bytes (for exampleBlock.blitinto another block) copies the pointer, not the text: it still points into the original block's storage, as a heap string's pointer still points into the string. Keep the source (the struct, or the packed block) alive while C uses the pointer;ffi::unpack::<S>(b)andffi::unpack::<S>(b, offset)read a new struct, and throw when the block is too short. Without the::<S>,unpacktakes the struct from the declaration it initializes or assigns (S v = ffi::unpack(b);, areturnof a function returningS); otherwise it isffi::unpack needs ::<S> when the struct type cannot be inferred from the declaration it initializes.- A struct passed or returned by value in a foreign function is converted to and from its C layout for the call. On the WebAssembly target that is a compile error: pass a pointer to packed bytes instead.
Examples
The same layout rules give C's padding: a byte followed by a float leaves seven bytes of padding.
Padding between fields
uses ffi;
use io::console;
use ffi;
@repr("C")
struct Mixed {
byte tag;
float value;
int16 count;
}
comptime int size = ffi::sizeOf::<Mixed>();
comptime int valueAt = ffi::offsetOf::<Mixed>("value");
comptime int countAt = ffi::offsetOf::<Mixed>("count");
console.writeln(size);
console.writeln(valueAt);
console.writeln(countAt);
24
8
16
A struct also reaches C as bytes: pack it, hand the block to any C function that takes a pointer, and
unpack what comes back. Here C's memcpy copies a packed struct and memset clears it:
Handing a packed struct to C
uses ffi;
use ffi;
use io::console;
@repr("C")
struct Pt {
int32 x;
int32 y;
}
@extern("c")
Ptr memcpy(Block dest, Block src, int n);
@extern("c")
Ptr memset(Block dest, int32 value, int n);
void main() {
Block original = ffi::pack(Pt(3, 4));
Block copy = Block(ffi::sizeOf::<Pt>());
memcpy(copy, original, copy.length());
Pt same = ffi::unpack::<Pt>(copy);
console.writeln(same.x);
console.writeln(same.y);
memset(copy, 0, copy.length());
Pt zero = ffi::unpack::<Pt>(copy);
console.writeln(zero.x + zero.y);
}
main();
3
4
0
pack and unpack need no foreign function: they convert between a struct and the bytes C would see,
so a layout can be checked, or filled by hand, without any library.
Packing a struct into C bytes
uses ffi;
use ffi;
use io::console;
@repr("C")
struct Pt {
int32 x;
int32 y;
}
void main() {
Block buf = ffi::pack(Pt(2, 3));
console.writeln(buf.length());
console.writeln(buf.int32At(4));
buf.setInt32(0, 40);
Pt back = ffi::unpack::<Pt>(buf);
console.writeln(back.x + back.y);
}
main();
8
3
43
Notes
@repr("C")does not change how Leviathan stores the struct; it only describes it to C.- The layout is computed once by the compiler and is the same for every way of running the program.
See also
- Foreign functions (@extern, @export) — Declare a C function with
@externand call it like any other function; which types cross to C and how, errors, variadic functions, exports and the build permission. - Value structs — Declare value types that are copied on every assignment, pass and return, with derived equality and explicit mutating methods.
- pack — Packs a
@repr("C")struct into a new block in C layout. - unpack — Reads a
@repr("C")struct from the start of a block in C layout. - sizeOf — The size in bytes of a
@repr("C")struct in C layout. - Block — A fixed-length, mutable buffer of bytes.