Skip to main content
Struct defines the memory layout of a C struct, supporting serialization/deserialization. It works with ffi.ptr to pass data to C functions.

Example

import { Struct, FFIType, ffi } from 'arkffi';

const Point = Struct({
  x: FFIType.int32,
  y: FFIType.int32,
});

const buf = Point.create({ x: 10, y: 20 });
const ptr = ffi.ptr(buf); // pass to C function

const read = Point.fromPtr(somePtr);
console.log(read.x, read.y);

Struct()

function Struct(fields: Record<string, string>): StructSchema;
ParameterTypeDescription
fieldsRecord<string, string>Field name to type code mapping

StructSchema

size

readonly size: number;
Total size of the struct in bytes, including padding.

create()

create(obj: Record<string, number | bigint>): ArrayBuffer;
Serialize an object to an ArrayBuffer.

fromPtr()

fromPtr(ptr: number, byteOffset?: number): Record<string, number>;
Read struct data from a raw pointer and deserialize.

get()

get(buf: ArrayBuffer, field: string): number;
Read a single field from an ArrayBuffer.

set()

set(buf: ArrayBuffer, field: string, value: number): void;
Set a single field in an ArrayBuffer.

ARM64 Alignment Rules

Type CodeC TypeSizeAlign
cchar / int8_t11
iint32_t / int44
lint64_t / uint64_t88
ddouble88
ffloat44
bbool11
sconst char* (pointer)88
p / kvoid* / function pointer88
const Mixed = Struct({ a: 'c', b: 'i', c: 'c' });
// a at offset 0 (1 byte), b at offset 4 (3 pad), c at offset 8 (1 byte)
// total = 12 bytes

Working with C Functions

const Point = Struct({ x: 'i', y: 'i' });
const lib = dlopen('lib.so', {
  setPoint: { args: [FFIType.ptr, FFIType.int32, FFIType.int32], returns: 'i' },
});

const buf = Point.create({ x: 0, y: 0 });
lib.symbols.setPoint(ffi.ptr(buf), 42, 99);

const result = Point.fromPtr(ffi.ptr(buf));
console.log(result.x, result.y); // 42, 99