Skip to main content

Function: defineStruct()

defineStruct(fields): StructDef

Describe a C struct as a list of fields, and get back a type that turns a plain JS object into struct bytes and back.

The layout is libffi's, so it is the platform's: offsets, size, alignment and padding all match what the C compiler did to the same struct.

import { defineStruct } from 'tjs:ffi';

// struct point { int x; int y; };
const Point = defineStruct([
['x', 'i32'],
['y', 'i32'],
]);

const bytes = Point.pack({ x: 3, y: 4 });

console.log(Point.unpack(bytes)); // { x: 3, y: 4 }

Parameters

fields

readonly StructField[]

[ name, type ] or [ name, type, options ] entries.

Returns

StructDef